Skip to content
Back to search

browser-relay

Let AI agents share your everyday, logged-in Chrome through a Skill + CLI — locally or across multiple machines.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/reliefeai--browser-relay/badge.svg)](/listings/reliefeai--browser-relay)

HTML

<a href="/listings/reliefeai--browser-relay"><img src="/api/listings/reliefeai--browser-relay/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Use Browser Relay in four steps. You need desktop Chrome plus Node.js/npm. The Chrome extension is loaded manually from its installed directory.

1. Install

npm install -g @linsoai/browser-relay

The package attempts to register a user-level background service. If your environment has no supported service manager, the verification step below gives the exact foreground command instead of failing with a stack trace.

2. Load the Chrome extension

Print the extension directory:

browser-relay path

Then open `chrome://extensions`, enable **Developer mode**, click **Load unpacked**, and select the `extension` directory printed by `browser-relay path`.

3. Verify the browser connection

Run one complete read-only diagnosis, then list the attached tabs:

browser-relay doctor
browser-relay tabs

`doctor` should report a healthy relay and connected extension. `tabs` should print at least one tab ID, title, and URL:

t_A7k2Pm9QxL    Example Domain    https://example.com/

If `doctor` says the service manager is unavailable, start the relay in another terminal and keep it running:

browser-relay

Then retry `browser-relay doctor`. If the relay is healthy but no tabs appear, reload the unpacked extension and retry `browser-relay tabs`. `doctor` never installs, restarts, or changes anything; add `--json` for automation.

<details> <summary>Background service, updates, and platform notes</summary>

The global install uses launchd on macOS, systemd-user on Linux, and a current-user Task Scheduler task on Windows. The service starts when you sign in. The Windows task uses your existing interactive login token with least privilege: it does not store a password, elevate itself, or run as SYSTEM. Organization policy can still block standard-user task registration.

`browser-relay install` safely refreshes a Browser Relay-owned service definition, starts it, and verifies the HTTP endpoint and installed version. Run it after an nvm upgrade or when `doctor` recommends it. It refuses to overwrite a same-name Windows task without Browser Relay's ownership marker. If a managed environment has no usable service manager, foreground mode (`browser-relay`) remains available.

Upgrade with `browser-relay update`. It installs `@linsoai/browser-relay@latest` globally, attempts to refresh the service, and prints a status check; the extension reloads itself on its next relay reconnect (within about 30 seconds).

</details>

4. Install the Agent Skill and run the first task

Browser Relay ships with an agent-friendly Skill. Choose the Agent explicitly so installation never opens an interactive selector:

browser-relay skill install --agent codex

# Claude Code, or both agents at once:
browser-relay skill install --agent claude-code
browser-relay skill install --agent codex claude-code

The command uses the standard `skills` CLI non-interactively, then reads every target `SKILL.md` back to verify it. Use `--agent universal` for agents that consume the standard `~/.agents/skills` directory, `browser-relay skill path` to inspect the bundled source, or plain `browser-relay skill` to print an install command for all agents (`--agent "*"`). Printing the command does not install anything. After installation, your agent can operate your own browser without opening a separate automation browser.

Give the agent a small read-only task first:

Use Browser Relay to tell me the title and URL of my current Chrome tab. Do not navigate.

The first successful response proves the full path works: Agent Skill → CLI → relay → extension → your existing Chrome tab.

If Browser Relay solves a workflow you actually have, starring the repository helps other agent builders find it.

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 443 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. <p align="center">
  2. <img src="extension/icons/icon128.png" width="96" height="96" alt="Browser Relay logo">
  3. </p>
  4. <h1 align="center">Browser Relay</h1>
  5. <p align="center">
  6. Let AI agents use the same Chrome browser you use every day.
  7. </p>
  8. <p align="center">
  9. <a href="https://www.npmjs.com/package/@linsoai/browser-relay"><img src="https://img.shields.io/npm/v/@linsoai/browser-relay.svg" alt="npm version"></a>
  10. <a href="https://www.npmjs.com/package/@linsoai/browser-relay"><img src="https://img.shields.io/npm/dm/@linsoai/browser-relay.svg" alt="npm downloads"></a>
  11. <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="MIT License"></a>
  12. <img src="https://img.shields.io/badge/agent-Skill%20%2B%20CLI-blue" alt="Agent Skill and CLI">
  13. <img src="https://img.shields.io/badge/remote-multi--machine-7c3aed" alt="Remote multi-machine control">
  14. <img src="https://img.shields.io/badge/local--first-127.0.0.1-111827" alt="Local first">
  15. </p>
  16. <p align="center">
  17. <a href="#quick-start">Quick Start</a>
  18. ·
  19. <a href="#agent-friendly-by-default">Agent Skill</a>
  20. ·
  21. <a href="#cli">CLI</a>
  22. ·
  23. <a href="#remote-control-remote-relay">Remote</a>
  24. ·
  25. <a href="https://github.com/reliefeai/browser-relay/blob/main/docs/README.zh-CN.md">中文</a>
  26. </p>
  27. <p align="center">
  28. <a href="https://github.com/reliefeai/browser-relay/blob/main/docs/assets/browser-relay-mobile-to-office.mp4">
  29. <img src="https://raw.githubusercontent.com/reliefeai/browser-relay/main/docs/assets/browser-relay-mobile-to-office.gif" width="960" alt="Illustrated Browser Relay workflow: an agent on a phone uses the Skill and CLI to operate a mock internal dashboard in the existing Chrome browser on an office machine">
  30. </a>
  31. </p>
  32. <p align="center"><sub>Illustrated workflow with mock data and no real credentials. Click the animation for the MP4 version.</sub></p>
  33. Browser Relay lets an AI agent join the Chrome browser you already use through an agent-native **Skill + CLI**. It does not launch a blank automation profile, keep pulling another browser window to the foreground, or make you log in again. You and the agent work in the same everyday browser — locally or across multiple machines.
  34. Use it when the task lives in a browser that already has the right login, extensions, device trust, or network access: operate your desktop browser from an agent on your phone, reach an internal system through the already-authenticated browser on your work computer, or let one agent work across browsers on several machines.
  35. ## Real Chrome, not a throwaway profile
  36. Most browser automation spins up a fresh, empty browser profile. That is fine for testing, but useless for agents that need your **authenticated** web apps — SaaS dashboards, admin panels, internal tools, documents, private sessions — where a headless browser or a fresh profile simply is not logged in.
  37. Browser Relay is that missing layer:
  38. - **Your actual Chrome session** — cookies, localStorage, extensions, and login state, shared as-is.
  39. - **No pop-up automation browser** — it never spawns a separate window or opens tabs behind your back; navigation reuses an attached tab.
  40. - **Local or remote** — one agent can drive browsers on this machine or several other machines through an outbound relay connection, with no public browser port exposed.
  41. - **Agent-first** — install the bundled Skill so Claude Code, Codex, Cursor, Windsurf, and other agents know when and how to use the inspectable CLI.
  42. - **Local-first boundary** — the relay binds to `127.0.0.1` by default.
  43. ## Provenance
  44. Based on [chengyixu/openclaw-browser-relay](https://github.com/chengyixu/openclaw-browser-relay), with auto-attach behavior inspired by [blakesabatinelli/openclaw-chrome-relay](https://github.com/blakesabatinelli/openclaw-chrome-relay). Repackaged as a general-purpose local browser bridge for AI agents, without the OpenClaw-specific gateway, token auth, or platform bindings.
  45. ## Architecture
  46. ```text
  47. Local
  48. AI Agent ──Skill + CLI──▶ Relay server (Node, 127.0.0.1)
  49. │ WebSocket
  50. ▼
  51. Chrome extension ──chrome.debugger / CDP──▶ your Chrome tabs
  52. Remote (Remote Relay)
  53. AI Agent ──HTTPS──▶ public relay (relay.linso.ai) ◀──WSS── Chrome extension ──▶ your Chrome tabs
  54. ```
  55. **Local mode** is the default: the agent talks to a relay server on `127.0.0.1`, which forwards Chrome DevTools Protocol commands to the extension.
  56. **Remote mode** exposes nothing. When you turn on Remote Relay, the extension connects *out* to a public relay service; a remote CLI reaches that same service, which routes each command down to your browser over the existing connection — no open ports, no local server on the network. Use the default hosted relay, or run your own on Cloudflare in one click (see below).
  57. ## Quick Start
  58. Use Browser Relay in four steps. You need desktop Chrome plus Node.js/npm. The Chrome extension is loaded manually from its installed directory.
  59. ### 1. Install
  60. ```bash
  61. npm install -g @linsoai/browser-relay
  62. ```
  63. The package attempts to register a user-level background service. If your environment has no supported service manager, the verification step below gives the exact foreground command instead of failing with a stack trace.
  64. ### 2. Load the Chrome extension
  65. Print the extension directory:
  66. ```bash
  67. browser-relay path
  68. ```
  69. Then open `chrome://extensions`, enable **Developer mode**, click **Load unpacked**, and select the `extension` directory printed by `browser-relay path`.
  70. ### 3. Verify the browser connection
  71. Run one complete read-only diagnosis, then list the attached tabs:
  72. ```bash
  73. browser-relay doctor
  74. browser-relay tabs
  75. ```
  76. `doctor` should report a healthy relay and connected extension. `tabs` should print at least one tab ID, title, and URL:
  77. ```text
  78. t_A7k2Pm9QxL Example Domain https://example.com/
  79. ```
  80. If `doctor` says the service manager is unavailable, start the relay in another terminal and keep it running:
  81. ```bash
  82. browser-relay
  83. ```
  84. Then retry `browser-relay doctor`. If the relay is healthy but no tabs appear, reload the unpacked extension and retry `browser-relay tabs`. `doctor` never installs, restarts, or changes anything; add `--json` for automation.
  85. <details>
  86. <summary>Background service, updates, and platform notes</summary>
  87. The global install uses launchd on macOS, systemd-user on Linux, and a current-user Task Scheduler task on Windows. The service starts when you sign in. The Windows task uses your existing interactive login token with least privilege: it does not store a password, elevate itself, or run as SYSTEM. Organization policy can still block standard-user task registration.
  88. `browser-relay install` safely refreshes a Browser Relay-owned service definition, starts it, and verifies the HTTP endpoint and installed version. Run it after an nvm upgrade or when `doctor` recommends it. It refuses to overwrite a same-name Windows task without Browser Relay's ownership marker. If a managed environment has no usable service manager, foreground mode (`browser-relay`) remains available.
  89. Upgrade with `browser-relay update`. It installs `@linsoai/browser-relay@latest` globally, attempts to refresh the service, and prints a status check; the extension reloads itself on its next relay reconnect (within about 30 seconds).
  90. </details>
  91. ### 4. Install the Agent Skill and run the first task
  92. Browser Relay ships with an agent-friendly Skill. Choose the Agent explicitly so installation never opens an interactive selector:
  93. ```bash
  94. browser-relay skill install --agent codex
  95. # Claude Code, or both agents at once:
  96. browser-relay skill install --agent claude-code
  97. browser-relay skill install --agent codex claude-code
  98. ```
  99. The command uses the standard `skills` CLI non-interactively, then reads every target `SKILL.md` back to verify it. Use `--agent universal` for agents that consume the standard `~/.agents/skills` directory, `browser-relay skill path` to inspect the bundled source, or plain `browser-relay skill` to print an install command for all agents (`--agent "*"`). Printing the command does not install anything. After installation, your agent can operate your own browser without opening a separate automation browser.
  100. Give the agent a small read-only task first:
  101. ```text
  102. Use Browser Relay to tell me the title and URL of my current Chrome tab. Do not navigate.
  103. ```
  104. The first successful response proves the full path works: Agent Skill → CLI → relay → extension → your existing Chrome tab.
  105. If Browser Relay solves a workflow you actually have, starring the repository helps other agent builders find it.
  106. ## Agent Friendly by Default
  107. Version **1.5.0** adds complete content reading, managed tab sessions and explicit handoff.
  108. See the [release notes and upgrade steps](docs/releases/v1.5.0.md) and [implementation and validation](docs/browser-use-parity.md).
  109. Development pushes do not publish npm packages; publication requires a manual workflow run with an explicit version and channel.
  110. Version 1.5 also adds a persistent JavaScript runtime, accessibility references and
  111. ordered action groups. Inspect with `browser-relay observe --tab <id>`, then
  112. execute a known sequence with `browser-relay actions --tab <id> --file actions.json`.
  113. One group runs inside the extension and returns the resulting state. Independent
  114. tabs may run concurrently; groups on one tab are serialized and cancellable.
  115. For scripts, use `browser-relay exec --file workflow.js`, or the MCP
  116. `browser_exec` tool to retain variables between calls. MCP screenshots are image
  117. content blocks. Visual click, drag and hover support screenshot coordinate
  118. mapping; background semantic clicks preserve the user's foreground tab. Visual
  119. mouse input reports `needs_foreground` when a visible tab is required.
  120. See the [runtime and SDK reference](skills/browser-relay/references/runtime.md)
  121. and [Codex comparison and measured results](docs/browser-use-comparison.md).
  122. Local scripts are trusted code with the agent's OS permissions; their separate
  123. process provides timeouts and reset, not a security sandbox. Remote devices only
  124. receive browser operations, never the agent's local JavaScript source.
  125. Browser Relay is designed to be comfortable for agents, not just low-level automation scripts.
  126. - The included Skill tells agents when to use Browser Relay and how to interact safely.
  127. - Page snapshots are annotated with links, buttons, inputs, and other interactive elements so agents can plan before acting.
  128. - Actions target existing attached tabs, keeping the user's browser context visible and predictable.
  129. - Stable CSS waits let agents wait for an element to attach or become visible instead of guessing with fixed sleeps.
  130. - Console and network capture record `console.*`, page exceptions, log entries, and request/response activity for debugging real-page behavior.
  131. ## CLI
  132. The CLI is the primary interface. For agents that can run shell commands, it is faster and less error-prone than hand-writing `curl` JSON:
  133. ```bash
  134. browser-relay tabs
  135. browser-relay console --tab t_A7k2Pm9QxL --limit 50
  136. browser-relay network --tab t_A7k2Pm9QxL --type response --status 500
  137. browser-relay snapshot --tab t_A7k2Pm9QxL --max-length 20000
  138. browser-relay wait 'button[type=submit]' --state visible --timeout 10000 --tab t_A7k2Pm9QxL
  139. browser-relay click 'button[type=submit]' --tab t_A7k2Pm9QxL
  140. browser-relay type 'hello world' --selector 'input[name=q]' --clear --submit
  141. browser-relay key Control+L
  142. browser-relay scroll down --amount 1000
  143. browser-relay screenshot /tmp/page.png --full-page
  144. browser-relay eval 'document.title'
  145. ```
  146. For long text or JavaScript, avoid shell escaping by reading from stdin:
  147. ```bash
  148. printf 'hello\nworld' | browser-relay type --selector textarea --stdin
  149. browser-relay eval --stdin < script.js
  150. ```
  151. All browser commands accept `--json` for the raw API response and `--tab <id>` to target a specific tab. When `--json` is used, a failed command prints the structured error payload and exits non-zero.
  152. ### Remote control (Remote Relay)
  153. To drive this browser from **another machine** — a CI box, a remote agent, a different network — turn on **Remote Relay** in the extension's Options page. The browser connects out to a public relay service (the hosted `relay.linso.ai` by default); nothing listens on a public port and no local server is exposed.
  154. Turning it on mints a secret **Device ID** — treat it like a password. Pass it to the same CLI commands from anywhere:
  155. ```bash
  156. browser-relay tabs --remote-device-id br-xxxx
  157. browser-relay eval "location.href" --remote-device-id br-xxxx
  158. # Save an alias once so you don't retype the id (remote ls / rm to manage):
  159. browser-relay remote add mymac br-xxxx
  160. browser-relay tabs --remote mymac
  161. ```
  162. Saved remote IDs are credentials. On POSIX systems Browser Relay stores them in
  163. `~/.browser-relay/remotes.json` and enforces `0700` on the directory and `0600` on
  164. the file, including tightening permissions created by older versions.
  165. `browser-relay remote ls`, including `--json`, returns only `(redacted)` IDs; it never
  166. prints the stored capability.
  167. **Run your own relay** instead of the hosted one — one click deploys the Worker in `hub/` to your own Cloudflare account:
  168. [![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/reliefeai/browser-relay/tree/main/hub)
  169. The button connects Cloudflare to your GitHub the first time (Workers Builds). Prefer the CLI? `git clone`, then `cd hub && npx wrangler deploy`. Either way, put the resulting `…workers.dev` URL in the Options page's *Public relay* field.
  170. The `remote-device-id` is a capability — anyone with it can control this browser while Remote Relay is on. Design notes: `docs/remote-control-hub.md`.
  171. ### CLI reference
  172. ```bash
  173. browser-relay # Run the relay server in the foreground
  174. browser-relay start # Start the background service
  175. browser-relay stop # Stop the background service
  176. browser-relay restart # Restart the background service
  177. browser-relay fix # Restart and clear stale session state (when tabs won't connect)
  178. browser-relay update # Update the global package and refresh the service
  179. browser-relay status # Show service state and HTTP health
  180. browser-relay doctor # Run a complete read-only installation diagnosis
  181. browser-relay logs # Follow the platform service logs
  182. browser-relay path # Print the Chrome extension directory
  183. browser-relay skill install --agent codex # Install/update and verify the Agent Skill
  184. browser-relay skill path # Print the bundled Skill directory
  185. browser-relay install # Register the background service
  186. browser-relay uninstall # Unregister the background service
  187. browser-relay tabs # List attached browser tabs
  188. browser-relay console # Print captured console/page errors
  189. browser-relay network # Print captured network requests/responses/failures
  190. browser-relay snapshot # Print annotated page text
  191. browser-relay wait # Wait for a CSS selector to attach or become visible
  192. browser-relay click # Click an element by CSS selector
  193. browser-relay type # Type text into the page
  194. browser-relay key # Press a key or shortcut
  195. browser-relay scroll # Scroll the page
  196. browser-relay screenshot # Save a PNG screenshot
  197. browser-relay eval # Evaluate JavaScript in the page
  198. browser-relay download # Print src/href for an element
  199. browser-relay download-start # Start a Chrome download
  200. browser-relay downloads # List Chrome downloads and events
  201. browser-relay remote # Manage remote aliases (add / ls / rm)
  202. browser-relay api-help # Show browser command examples
  203. ```
  204. ## MCP
  205. After installing the npm package, use `browser-relay-mcp` directly:
  206. ```json
  207. {
  208. "mcpServers": {
  209. "browser": {
  210. "command": "browser-relay-mcp",
  211. "env": {
  212. "BROWSER_RELAY_URL": "http://127.0.0.1:18795"
  213. }
  214. }
  215. }
  216. }
  217. ```
  218. The MCP server exposes high-level tools such as `browser_tabs`, `browser_snapshot`, `browser_wait`, `browser_click`, `browser_type`, `browser_key`, and `browser_screenshot`.
  219. ## HTTP API
  220. The HTTP API is the stable integration surface for code and custom tools. For interactive agent work, prefer the CLI above.
  221. Errors use a structured shape across HTTP, CLI `--json`, and MCP tool errors:
  222. ```json
  223. { "ok": false, "code": "invalid_request", "error": "url is required", "message": "url is required", "status": 400, "retryable": false }
  224. ```
  225. ```bash
  226. # List attached tabs
  227. curl http://127.0.0.1:18795/api/tabs
  228. # Take a text snapshot of a page
  229. curl "http://127.0.0.1:18795/api/snapshot?tabId=t_A7k2Pm9QxL"
  230. # Wait until an element is visible (attached is also supported)
  231. curl -X POST http://127.0.0.1:18795/api/wait \
  232. -H "Content-Type: application/json" \
  233. -d '{"tabId":"t_A7k2Pm9QxL","selector":"button.submit","state":"visible","timeoutMs":10000}'
  234. # Read captured console/page errors
  235. curl "http://127.0.0.1:18795/api/console?tabId=t_A7k2Pm9QxL&limit=50"
  236. # Read captured network activity (sensitive headers are redacted)
  237. curl "http://127.0.0.1:18795/api/network?tabId=t_A7k2Pm9QxL&type=response&status=500"
  238. # Click an element
  239. curl -X POST http://127.0.0.1:18795/api/click \
  240. -H "Content-Type: application/json" \
  241. -d '{"tabId":"t_A7k2Pm9QxL","selector":"button.submit"}'
  242. ```
  243. | Endpoint | Method | Description |
  244. | --- | --- | --- |
  245. | `/` | GET/HEAD | Health check |
  246. | `/api/debug` | GET | Server diagnostics |
  247. | `/api/tabs` | GET | List attached tabs |
  248. | `/api/console` | GET | Read captured console/page error entries |
  249. | `/api/console/clear` | POST | Clear captured console entries |
  250. | `/api/network` | GET | Read captured Network.* request/response/failure entries |
  251. | `/api/network/clear` | POST | Clear captured network entries |
  252. | `/api/navigate` | POST | Navigate an attached tab |
  253. | `/api/snapshot` | GET | Get annotated text or raw HTML |
  254. | `/api/wait` | POST | Wait for a CSS selector to attach or become visible |
  255. | `/api/click` | POST | Click an element by CSS selector |
  256. | `/api/type` | POST | Type into an input |
  257. | `/api/key` | POST | Press a key or keyboard shortcut |
  258. | `/api/scroll` | POST | Scroll the page |
  259. | `/api/screenshot` | GET/POST | Capture a PNG screenshot; full-page mode returns capture strategy/size metadata |
  260. | `/api/eval` | POST | Evaluate JavaScript in the page |
  261. | `/api/download` | POST | Extract an element URL |
  262. | `/api/download/start` | POST | Start a real Chrome download from a URL |
  263. | `/api/downloads` | GET | List Chrome downloads and recent download events |
  264. | `/api/downloads/clear` | POST | Clear captured download events |
  265. Real Chrome downloads require the extension's `downloads` permission. After upgrading from an older Browser Relay version, reload the unpacked extension in `chrome://extensions`.
  266. The same endpoints are reachable remotely: a CLI running with `--remote-device-id` sends them through the public relay to the browser.
  267. ## Configuration
  268. | Environment variable | Default | Description |
  269. | --- | --- | --- |
  270. | `BROWSER_RELAY_URL` | `http://127.0.0.1:18795` | Relay base URL used by CLI browser commands and MCP |
  271. | `BROWSER_RELAY_HOST` | `127.0.0.1` | HTTP and WebSocket bind address |
  272. | `BROWSER_RELAY_PORT` | `18795` | HTTP and WebSocket port |
  273. | `BROWSER_RELAY_REMOTE_DEVICE_ID` | — | Remote Device ID (or alias) used when no `--remote-device-id` flag is passed |
  274. | `BROWSER_RELAY_REMOTE_HOST` | `https://relay.linso.ai` | Public relay URL for remote commands |
  275. The Chrome extension port can be changed from the extension Options page.
  276. Service files:
  277. ```text
  278. macOS: ~/Library/LaunchAgents/org.browser-relay.service.plist
  279. Linux: ~/.config/systemd/user/browser-relay.service
  280. Windows task: BrowserRelay
  281. Windows definition: %LOCALAPPDATA%\BrowserRelay\task.xml
  282. ```
  283. Logs:
  284. ```text
  285. macOS: /tmp/browser-relay.log, /tmp/browser-relay.error.log
  286. Linux: journalctl --user -u browser-relay
  287. Windows: %LOCALAPPDATA%\BrowserRelay\logs\browser-relay.log
  288. %LOCALAPPDATA%\BrowserRelay\logs\browser-relay.error.log
  289. ```
  290. On Windows, `uninstall` removes only the Browser Relay scheduled task and its generated XML definition. It preserves logs for diagnosis and never kills an unrelated process that happens to use port `18795`.
  291. ### Hiding the "debugging this browser" infobar
  292. Whenever the extension has a debugger attached, Chrome shows a mandatory
  293. `"Browser Relay" started debugging this browser` bar at the top of the page.
  294. No extension API can remove it — it is Chrome's built-in anti-abuse warning.
  295. Two ways to deal with it:
  296. - **Automatic (default):** the extension soft-detaches idle tabs after 10 min, so
  297. the bar disappears on its own while you're not using it and re-attaches on the
  298. next command. Nothing to configure.
  299. - **Remove it entirely:** launch Chrome with the `--silent-debugger-extension-api`
  300. flag, which suppresses the bar for the debugger extension API. You must fully
  301. quit Chrome first (`open --args` only passes flags to a cold start):
  302. ```bash
  303. # macOS
  304. osascript -e 'quit app "Google Chrome"'
  305. open -a "Google Chrome" --args --silent-debugger-extension-api
  306. ```
  307. To make it stick, always launch Chrome this way (e.g. a shell alias or a
  308. `.command` launcher) — a normal Dock click won't carry the flag.
  309. Trade-off: this weakens a security protection — *any* extension with the
  310. `debugger` permission can then silently attach without warning. Fine for
  311. personal use as long as you understand what it disables.
  312. ## Development
  313. Release setup and manual workflow commands: [Publishing with npm OIDC](docs/publishing.md).
  314. ```bash
  315. npm install
  316. npm start
  317. npm run mcp
  318. npm test
  319. ```
  320. Load the local `extension/` directory from `chrome://extensions` in Developer mode.
  321. ## Security
  322. - The extension uses Chrome's `debugger` permission. Install only versions you trust.
  323. - The relay binds to `127.0.0.1` by default. Do not expose it to the public internet.
  324. - Remote Relay never opens a port: the browser connects out to the public relay, which only holds a hash of your Device ID secret in memory. Treat the Device ID like a password; anyone with it can control the browser while Remote Relay is on.
  325. - Browser Relay gives agents access to the same browser state you have, so treat enabled agents as trusted local software.
  326. ## License
  327. MIT
server/windows-service.js · Bundled script · 360 lines · 1 finding marked
  1. import { spawnSync } from "node:child_process";
  2. import { existsSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
  3. import { homedir } from "node:os";
  4. import { dirname, join } from "node:path";
  5. export const WINDOWS_TASK_NAME = "BrowserRelay";
  6. export const WINDOWS_TASK_SOURCE = "https://github.com/reliefeai/browser-relay";
  7. export const WINDOWS_TASK_OWNER = "browser-relay:service:v1";
  8. function xmlEscape(value) {
  9. return String(value)
  10. .replace(/&/g, "&amp;")
  11. .replace(/</g, "&lt;")
  12. .replace(/>/g, "&gt;")
  13. .replace(/\"/g, "&quot;")
  14. .replace(/'/g, "&apos;");
  15. }
  16. // Task Scheduler stores Exec.Arguments as one Windows command line. Quote each
  17. // argv value using the CommandLineToArgvW backslash rules so spaces, ampersands,
  18. // exclamation marks, parentheses, and trailing slashes survive unchanged.
  19. export function quoteWindowsArg(value) {
  20. const input = String(value);
  21. let output = "\"";
  22. let backslashes = 0;
  23. for (const char of input) {
  24. if (char === "\\") {
  25. backslashes += 1;
  26. continue;
  27. }
  28. if (char === "\"") {
  29. output += "\\".repeat(backslashes * 2 + 1) + "\"";
  30. backslashes = 0;
  31. continue;
  32. }
  33. output += "\\".repeat(backslashes) + char;
  34. backslashes = 0;
  35. }
  36. return output + "\\".repeat(backslashes * 2) + "\"";
  37. }
  38. export function windowsServicePaths(options = {}) {
  39. const home = options.home || homedir();
  40. const localAppData = options.localAppData
  41. || process.env.LOCALAPPDATA?.trim()
  42. || join(home, "AppData", "Local");
  43. const root = join(localAppData, "BrowserRelay");
  44. const logs = join(root, "logs");
  45. return {
  46. root,
  47. logs,
  48. taskXml: join(root, "task.xml"),
  49. stdoutLog: join(logs, "browser-relay.log"),
  50. stderrLog: join(logs, "browser-relay.error.log"),
  51. };
  52. }
  53. export function windowsTaskArguments({ serviceEntryPath, cliPath, stdoutLog, stderrLog }) {
  54. return [
  55. serviceEntryPath,
  56. "--entry",
  57. cliPath,
  58. "--stdout-log",
  59. stdoutLog,
  60. "--stderr-log",
  61. stderrLog,
  62. ].map(quoteWindowsArg).join(" ");
  63. }
  64. export function windowsTaskXml({
  65. sid,
  66. nodePath,
  67. serviceEntryPath,
  68. cliPath,
  69. stdoutLog,
  70. stderrLog,
  71. taskName = WINDOWS_TASK_NAME,
  72. }) {
  73. if (!/^S-\d-(?:\d+-)+\d+$/i.test(sid)) throw new Error("Could not determine the current Windows user SID");
  74. const args = windowsTaskArguments({ serviceEntryPath, cliPath, stdoutLog, stderrLog });
  75. const taskUri = `\\${String(taskName).replace(/^\\+/, "")}`;
  76. return `<?xml version="1.0" encoding="UTF-16"?>
  77. <Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  78. <RegistrationInfo>
  79. <Description>Runs Browser Relay for the current signed-in user.</Description>
  80. <Source>${xmlEscape(WINDOWS_TASK_SOURCE)}</Source>
  81. <Documentation>${xmlEscape(WINDOWS_TASK_OWNER)}</Documentation>
  82. <URI>${xmlEscape(taskUri)}</URI>
  83. </RegistrationInfo>
  84. <Triggers>
  85. <LogonTrigger>
  86. <Enabled>true</Enabled>
  87. <UserId>${xmlEscape(sid)}</UserId>
  88. </LogonTrigger>
  89. </Triggers>
  90. <Principals>
  91. <Principal id="Author">
  92. <UserId>${xmlEscape(sid)}</UserId>
  93. <LogonType>InteractiveToken</LogonType>
  94. <RunLevel>LeastPrivilege</RunLevel>
  95. </Principal>
  96. </Principals>
  97. <Settings>
  98. <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
  99. <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
  100. <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
  101. <AllowHardTerminate>true</AllowHardTerminate>
  102. <StartWhenAvailable>true</StartWhenAvailable>
  103. <AllowStartOnDemand>true</AllowStartOnDemand>
  104. <Enabled>true</Enabled>
  105. <Hidden>false</Hidden>
    • Note: Usual in code (tag names in paths and patterns): Contains a <hidden> block, a common wrapper for instructions hidden in a tool description
    • Line 113 on GitHub
  106. <RunOnlyIfIdle>false</RunOnlyIfIdle>
  107. <WakeToRun>false</WakeToRun>
  108. <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
  109. <Priority>7</Priority>
  110. <RestartOnFailure>
  111. <Interval>PT1M</Interval>
  112. <Count>3</Count>
  113. </RestartOnFailure>
  114. </Settings>
  115. <Actions Context="Author">
  116. <Exec>
  117. <Command>${xmlEscape(nodePath)}</Command>
  118. <Arguments>${xmlEscape(args)}</Arguments>
  119. <WorkingDirectory>${xmlEscape(dirname(cliPath))}</WorkingDirectory>
  120. </Exec>
  121. </Actions>
  122. </Task>
  123. `;
  124. }
  125. function decodeWindowsOutput(value) {
  126. if (!value) return "";
  127. if (typeof value === "string") return value;
  128. const buffer = Buffer.from(value);
  129. if (buffer[0] === 0xff && buffer[1] === 0xfe) return buffer.subarray(2).toString("utf16le");
  130. let zeroes = 0;
  131. for (let i = 1; i < Math.min(buffer.length, 200); i += 2) {
  132. if (buffer[i] === 0) zeroes += 1;
  133. }
  134. if (zeroes > 10) return buffer.toString("utf16le");
  135. return buffer.toString("utf8");
  136. }
  137. export function invokeSchtasks(args) {
  138. const result = spawnSync("schtasks.exe", args, {
  139. encoding: null,
  140. stdio: ["ignore", "pipe", "pipe"],
  141. windowsHide: true,
  142. timeout: 15_000,
  143. });
  144. return {
  145. ...result,
  146. stdout: decodeWindowsOutput(result.stdout),
  147. stderr: decodeWindowsOutput(result.stderr),
  148. };
  149. }
  150. export function schtasksError(action, result) {
  151. if (result?.error) return `${action}: ${result.error.message}`;
  152. const detail = String(result?.stderr || result?.stdout || "").trim().split(/\r?\n/)[0];
  153. return `${action} failed${result?.status == null ? "" : ` with exit code ${result.status}`}${detail ? `: ${detail}` : ""}`;
  154. }
  155. export function windowsTaskCommandArgs(command, options = {}) {
  156. const taskName = options.taskName || WINDOWS_TASK_NAME;
  157. if (command === "query") return ["/Query", "/TN", taskName, "/XML"];
  158. if (command === "list") return ["/Query", "/FO", "CSV", "/NH"];
  159. if (command === "run") return ["/Run", "/TN", taskName];
  160. if (command === "end") return ["/End", "/TN", taskName];
  161. if (command === "delete") return ["/Delete", "/TN", taskName, "/F"];
  162. if (command === "create") {
  163. if (!options.taskXml) throw new Error("taskXml is required for the create command");
  164. return [
  165. "/Create", "/XML", options.taskXml, "/TN", taskName,
  166. ...(options.force === true ? ["/F"] : []),
  167. ];
  168. }
  169. throw new Error(`Unknown Windows task command: ${command}`);
  170. }
  171. function normalizeTaskName(value) {
  172. return String(value).trim().replace(/^\\+/, "").toLowerCase();
  173. }
  174. export function parseWindowsTaskNames(output) {
  175. const names = [];
  176. for (const rawLine of String(output || "").replace(/^\uFEFF/, "").split(/\r?\n/)) {
  177. const line = rawLine.trim();
  178. if (!line) continue;
  179. if (line.startsWith('"')) {
  180. let value = "";
  181. for (let i = 1; i < line.length; i++) {
  182. if (line[i] !== '"') {
  183. value += line[i];
  184. continue;
  185. }
  186. if (line[i + 1] === '"') {
  187. value += '"';
  188. i += 1;
  189. continue;
  190. }
  191. break;
  192. }
  193. names.push(value);
  194. } else {
  195. names.push(line.split(",", 1)[0]);
  196. }
  197. }
  198. return names;
  199. }
  200. export function isBrowserRelayTaskXml(xml) {
  201. const value = String(xml || "");
  202. return /<Source>\s*https:\/\/github\.com\/reliefeai\/browser-relay\s*<\/Source>/i.test(value)
  203. && /<Documentation>\s*browser-relay:service:v1\s*<\/Documentation>/i.test(value);
  204. }
  205. export function inspectWindowsTask(options = {}) {
  206. const runner = options.runner || invokeSchtasks;
  207. const result = runner(windowsTaskCommandArgs("query", options));
  208. if (result.error) {
  209. return {
  210. checked: false,
  211. registered: false,
  212. owned: false,
  213. xml: "",
  214. error: schtasksError("Task Scheduler query", result),
  215. };
  216. }
  217. if (result.status === 0) {
  218. const xml = String(result.stdout || "").replace(/^\uFEFF/, "");
  219. if (!/<Task(?:\s|>)/i.test(xml)) {
  220. return {
  221. checked: false,
  222. registered: true,
  223. owned: false,
  224. xml,
  225. error: "Task Scheduler returned an invalid XML definition for BrowserRelay",
  226. };
  227. }
  228. return {
  229. checked: true,
  230. registered: true,
  231. owned: isBrowserRelayTaskXml(xml),
  232. xml,
  233. error: null,
  234. };
  235. }
  236. // schtasks uses a non-zero exit for both "not found" and operational
  237. // failures. A successful all-task listing lets us prove absence without
  238. // parsing localized error text; if the name is present or listing fails, the
  239. // result remains an error and no mutating command is allowed.
  240. const listed = runner(windowsTaskCommandArgs("list", options));
  241. if (listed.error || listed.status !== 0) {
  242. return {
  243. checked: false,
  244. registered: false,
  245. owned: false,
  246. xml: "",
  247. error: schtasksError("Task Scheduler query", listed),
  248. };
  249. }
  250. const target = normalizeTaskName(options.taskName || WINDOWS_TASK_NAME);
  251. const nameExists = parseWindowsTaskNames(listed.stdout).some((name) => normalizeTaskName(name) === target);
  252. if (nameExists) {
  253. return {
  254. checked: false,
  255. registered: true,
  256. owned: false,
  257. xml: "",
  258. error: schtasksError("BrowserRelay task XML query", result),
  259. };
  260. }
  261. return {
  262. checked: true,
  263. registered: false,
  264. owned: false,
  265. xml: "",
  266. error: null,
  267. };
  268. }
  269. export function currentWindowsSid(options = {}) {
  270. const runner = options.runner || ((args) => {
  271. const result = spawnSync("whoami.exe", args, {
  272. encoding: "utf8",
  273. windowsHide: true,
  274. timeout: 5_000,
  275. });
  276. return result;
  277. });
  278. const result = runner(["/user", "/fo", "csv", "/nh"]);
  279. if (result.error || result.status !== 0) throw new Error(schtasksError("Windows user lookup", result));
  280. const sid = String(result.stdout || "").match(/S-\d-(?:\d+-)+\d+/i)?.[0];
  281. if (!sid) throw new Error("Could not determine the current Windows user SID");
  282. return sid;
  283. }
  284. export function runWindowsTaskCommand(command, options = {}) {
  285. const runner = options.runner || invokeSchtasks;
  286. return runner(windowsTaskCommandArgs(command, options));
  287. }
  288. export function installWindowsTask(options) {
  289. const runner = options.runner || invokeSchtasks;
  290. const paths = options.paths || windowsServicePaths();
  291. const sid = options.sid || currentWindowsSid();
  292. const existing = inspectWindowsTask({ ...options, runner });
  293. if (!existing.checked) throw new Error(existing.error);
  294. if (existing.registered && !existing.owned) {
  295. throw new Error("A task named BrowserRelay already exists but is not owned by Browser Relay; refusing to overwrite it");
  296. }
  297. mkdirSync(paths.logs, { recursive: true });
  298. const xml = windowsTaskXml({
  299. sid,
  300. nodePath: options.nodePath,
  301. serviceEntryPath: options.serviceEntryPath,
  302. cliPath: options.cliPath,
  303. stdoutLog: paths.stdoutLog,
  304. stderrLog: paths.stderrLog,
  305. taskName: options.taskName || WINDOWS_TASK_NAME,
  306. });
  307. // Task Scheduler's native format is UTF-16. Writing it this way also keeps
  308. // non-ASCII Windows user and npm paths independent of the active code page.
  309. writeFileSync(paths.taskXml, `\uFEFF${xml}`, "utf16le");
  310. // Updating a running task does not replace its current process. End the old
  311. // instance first, then idempotently overwrite and immediately test the task.
  312. if (existing.registered) runner(windowsTaskCommandArgs("end", options));
  313. const created = runner(windowsTaskCommandArgs("create", {
  314. ...options,
  315. taskXml: paths.taskXml,
  316. force: existing.registered,
  317. }));
  318. if (created.error || created.status !== 0) throw new Error(schtasksError("Task Scheduler registration", created));
  319. const started = runner(windowsTaskCommandArgs("run", options));
  320. if (started.error || started.status !== 0) throw new Error(schtasksError("Task Scheduler start", started));
  321. return { paths, sid };
  322. }
  323. export function uninstallWindowsTask(options = {}) {
  324. const runner = options.runner || invokeSchtasks;
  325. const paths = options.paths || windowsServicePaths();
  326. const state = inspectWindowsTask({ ...options, runner });
  327. if (!state.checked) throw new Error(state.error);
  328. if (state.registered && !state.owned) {
  329. throw new Error("A task named BrowserRelay exists but is not owned by Browser Relay; refusing to stop or delete it");
  330. }
  331. if (state.registered) {
  332. runner(windowsTaskCommandArgs("end", options));
  333. const deleted = runner(windowsTaskCommandArgs("delete", options));
  334. if (deleted.error || deleted.status !== 0) throw new Error(schtasksError("Task Scheduler removal", deleted));
  335. }
  336. if (existsSync(paths.taskXml)) unlinkSync(paths.taskXml);
  337. return { removedTask: state.registered, paths };
  338. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.