Repository navigation
Delete the in-app browser loopback firewall - #1537
Conversation
|
🚨 SLOP COP 🚨 · I am the SlopCop. I am reviewing this pull request now. I will check security, code quality, performance, architecture, and the user flow. |
| }), | ||
| }); | ||
| }); | ||
| hardenedSession = browserSession; |
There was a problem hiding this comment.
🚨 slopcop/review — High: This deletion lets public pages open local WebSockets.
Electron 41.7 uses Chromium 146. Chromium 146 has no Local Network Access check for WebSockets.
I confirmed this path with Electron. A public HTTPS page opened a ws://127.0.0.1 socket under these permission handlers.
The BB service guards protect BB services only. Other loopback and LAN services can still trust local clients.
Keep a narrow request guard. Allow local source pages to use local ports, and deny public source pages.
There was a problem hiding this comment.
Confirmed, and I reproduced it independently rather than taking it. Real Electron 41 driving the production manager, with the page served from a public hostname mapped to this machine (--host-resolver-rules="MAP public.example 127.0.0.1"):
### bb manager (this PR), page on PUBLIC hostname
[backend] WS ACCEPTED
[backend] HTTP REACHED
[report] public-page-ws-OPEN
[report] public-page-fetch-SENT
Your claim about Chromium is right. A plain Chromium window with identical webPreferences and no bb hardening behaves the same, so Chromium 146 applies no Local Network Access check on this path. I also ruled out the permission handlers: the only permission requested is background-sync, and allowing everything changes nothing.
I also confirmed it is not pre-existing. Before this PR a public main frame committed no local origin key, so shouldBlockBrowserRequest denied its loopback subresources. This PR introduces it.
I am not implementing the narrow guard here, and I want to be explicit about why rather than hide behind scope. This deletion is a direct product instruction from the repo owner:
"delete all of the code that stops the in app browser from accessing loopback. This is intended behavior and I am fine if they hit the bb server. That code that is there is misguided. This is local software that they control."
Your finding identifies a real gap in that rationale: "local software that they control" describes a local page. It does not describe a public website that merely happens to be open in the panel. That distinction is worth deciding on, and it is the owner's call — reversing an explicit instruction inside the PR that carries it out is not mine to make.
So: filed as #1539 with the full reproduction, both control runs, and two concrete options — a source-origin-based request guard (your suggestion, which is the deleted firewall minus the same-origin-and-port rule that caused #1452), or accepting it as a documented posture. I have also put a prominent warning at the top of this PR body so it is decided before merge rather than discovered after.
One correction for the record: #1536 does not leave bb's own services exposed — the bb server, the host-daemon local API, and the machine-auth proxy each reject foreign browser origins. What is uncovered is everything else on the user's loopback and LAN, which is exactly the point you are making.
There was a problem hiding this comment.
Confirmed, and it is the same root cause as the WebSocket finding: after this PR a public page reaches local targets, here through window.open rather than a subresource. You are right that the rate limit bounds the count and not the target.
Two details I verified rather than assumed:
- The native OS popup is still always denied —
setWindowOpenHandlerreturns{ action: "deny" }unconditionally, and an allowed URL is surfaced to the renderer as an in-panel tab instead. So the exposure is a new tab in the panel, not an uncontrolled window. - A main-frame navigation to a loopback address was already allowed before this PR;
shouldBlockBrowserRequestpermitted top-levelhttp(s)GET navigation to loopback and only blocked non-main-frame requests. What this PR changes is that the popup path no longer denies loopback and LAN targets, becauseisAllowedPublicBrowserPopupUrlused the host classification being deleted.
Tracked in #1539 alongside the subresource case, since a fix for one should cover the other — your suggestion of passing the source URL into the policy is recorded there as part of option 1.
Declining to implement it in this PR for the same reason: it reverses the explicit instruction this PR exists to carry out. Flagged at the top of the PR body so it is decided before merge.
| return true; | ||
| } | ||
| return targetOriginKey !== args.currentMainFrameLocalOriginKey; | ||
| return { openTabUrl: isAllowedBrowserUrl(url) ? url : null }; |
There was a problem hiding this comment.
🚨 slopcop/review — Medium: A page can open local targets without a user address action.
The page controls window.open. This policy accepts each HTTP target and creates a new panel tab.
Chromium applies no Local Network Access check to a main-frame navigation. The popup limit controls the count, not the target.
Pass the source URL to this policy. Allow a local target only from a local source or a direct user action.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5
This change removes a network fence inside the BB browser. It lets local apps connect across two ports.
It is like a gate for one friend that all visitors can use.
Findings
-
High: A public page can open a loopback or LAN WebSocket.
Electron 41.7 uses Chromium 146. Chromium adds Local Network Access checks for WebSockets in version 147.
I confirmed the defect with a hidden Electron test. A public HTTPS page opened a loopback WebSocket under the production permission policy.
BB protects its services, but this change exposes other local services. Keep a narrow public-to-local request guard.
-
Medium: A hostile page can open loopback or LAN tabs through
window.open.Chromium does not apply Local Network Access checks to main-frame navigation. The rate limit controls the tab count only.
Permit a local target only from a local source page or a direct user action.
-
Medium: A local page can now change BB enrollment-key state through a blind cross-port request.
/internal/hosts/enroll-keytrusts the loopback connection. It acceptstext/plainJSON and has no browser origin guard.Add the origin and JSON mutation guard to this route.
Tests and architecture
The PR has no automated test for the reported cross-port WebSocket path. Add an Electron test for allowed and denied paths.
The deletion leaves entriesByWebContentsId with no reads. Remove the map and its set and delete calls.
The manager test also keeps unused navigation helper code. Remove it with this deletion.
The app already classifies local browser addresses in apps/app/src/lib/browser-url.ts. Use one shared pure classifier if you restore this policy.
The change removes work from each request. I found no performance defect, request loop, or resource leak.
Validation
git diff --check passed. The desktop type check passed. Both changed test files passed.
The desktop suite passed 211 of 212 tests. The unrelated Electron preload smoke test timed out.
Dev Browser cannot control an Electron WebContentsView. The hidden Electron probe tested the critical WebSocket path and returned probe-result:open.
The WebSocket defect must be fixed before merge. I posted this as a comment-only review, as required.
dc6c77b to
dd65a45
Compare
The in-app browser blocked a browsed page from reaching loopback and LAN addresses: subresources, fetch/XHR, iframes, and WebSockets were allowed only back to the page's own exact origin, port included. That is why a local app whose frontend and WebSocket backend sit on different ports never connected. This is local software the user controls, and reaching bb's own server from a page they opened themselves is fine. Layer 1 gives every bb service its own origin guard, which is the control that actually belongs to each service. Deleted: shouldBlockBrowserRequest, the loopback/private host classification and its IPv4/IPv6 helpers, the local-origin-key helpers, and the session.webRequest.onBeforeRequest wiring, along with every test for them. Kept: isAllowedBrowserUrl, so file:, javascript:, data:, and custom schemes still cannot be navigated to, and the popup rate limit. Popups to loopback and LAN addresses are now surfaced as in-panel tabs like any other http(s) URL — opening one is the same act as typing the address. Fixes #1452 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
dd65a45 to
2481fea
Compare
**Layer 1 of 2.** Prerequisite for #1537, which deletes the in-app browser's loopback firewall. This layer must land first: it gives each bb service the origin guard that the firewall was standing in for. ## Summary CORS decides whether a browser may *read* a response. It never stops the request being sent and acted on. A `no-cors` POST with a simple content type skips the preflight entirely, and the typed route parser reads the body with `c.req.json()` regardless of content type — so a page on any origin could drive these APIs blind, seeing nothing but changing state. Three services now reject a foreign browser origin outright: | Service | Before | After | |---|---|---| | Server `/api/v1/*` | `cors()` only. `browserRequestProblem` was applied to `/ws`, `/ws/terminals/:id`, and routes in `plugins.ts` / `files.ts` — not the rest. | Origin guard on the whole subtree. | | Host daemon local API | Computed an allow predicate for `cors({origin})` but never rejected on it. | The same predicate enforced as a request guard. | | Machine-auth proxy | Nothing. It stamps `x-bb-connect-machine` onto everything it forwards. | `Origin` + `Sec-Fetch-Site`, plus a `Host` authority check. | **Excluded on purpose: `/api/v1/plugins/<id>/http/*`.** A plugin declares its own auth mode per route — `local`, `token`, or `none` — and `none` is deliberately reachable from any origin while `token` authenticates with a secret. `registerPluginRoutes` applies the right check per route; a blanket guard would pre-empt it. I found this by running the suite, not by reading: three `plugin-wire` tests failed, including `auth "none" passes foreign origins through`. **`requireJsonForMutation` is deliberately NOT set** on `/api/v1/*`. It answers 415 to any mutation without `application/json`, which would break every existing `curl -d` caller. The origin check alone stops browser CSRF, because a browser always sends `Origin` on a cross-origin mutation. **`Sec-Fetch-Mode` is deliberately not a discriminator** on the proxy. Node's own `fetch` sends `sec-fetch-mode: cors`, so keying on it rejects the runtime processes the proxy exists to serve — three proxy tests went red when I tried. ## DNS rebinding (from review) SlopCop found that `isTrustedOrigin` trusts an origin matching the authority the client addressed, and a page on a public name resolving to this machine controls both `Origin` and `Host`. Reproduced: `Origin: http://rebind.example:<port>` with a matching `Host` returned **200**. **Fixed for the host-daemon local API** (6018b61). That API binds `127.0.0.1`, so a genuine caller always addresses it by a loopback name or a bare address; the self-origin branch now requires that. Configured allowlists are untouched. Regression test included, over `http.request` since `fetch` drops a `Host` override. **Not fixed for the server**, deliberately. I implemented the same rule there and the existing suite rejected it: ``` plugin-wire.test.ts > local auth rejects foreign origins but tolerates host-bound LAN/Tailscale serving AssertionError: expected 403 to be 200 ``` bb deliberately supports being served at an arbitrary DNS name bound to the request `Host` — `https://bb.lan.test` is asserted to return 200, with a comment saying so. That is header-indistinguishable from `rebind.example`, so closing the bypass necessarily drops unconfigured DNS-name serving. That is a decision about supported deployment shapes, not a bug fix, so it is filed rather than made here. Scope note: this is **pre-existing**, not introduced here — `browserRequestProblem` has guarded `/ws` and the plugin and file routes with this same branch all along. This PR widens its reach to the rest of `/api/v1`, which is strictly more protection than the `cors()`-only state it replaces. ## Verification Everything below was tested, not reasoned about. `apps/server/test/security/api-origin-guard.test.ts` runs against a real server. **1. bb Connect through the tunnel — the highest risk, and it is safe.** Not because the guard is lenient, but because the tunnel already rewrites the origin. For the bare-handle path (the bb server, which is what `https://bee.getbb.app` uses), `resolveStreamOrigin` in `plugins/connect/src/tunnel.ts` sets `publicOrigin` to the credential's server origin, and `headersForLoopbackRequest` in `@bb/tunnel-client` rewrites a matching `Origin` to the loopback origin while dropping the public `Host`. The local server therefore sees `Origin: http://127.0.0.1:38886` against a matching `Host` — same-origin, allowed. Two tests pin this: one asserts the rewritten shape passes, and one asserts an **unrewritten** `https://bee.getbb.app` gets 403. That second test is the canary — if the rewrite ever regresses, it names the cause instead of leaving a mysterious lockout. **2. Sandboxed iframes.** The HTML/file previews use `sandbox="allow-scripts"` without `allow-same-origin`, so their origin is opaque and they send `Origin: null`, which fails the parse and gets 403. What that does and does not affect: - The iframe's own document load is a **navigation** and sends no `Origin` → unaffected. `plugins/inline-vis` loads `/api/v1/threads/<id>/worktree/files/...` directly as the frame `src`, and it keeps working. - Sub-resource loads (`<script src>`, `<img>`) send no `Origin` → unaffected. - Only `fetch`/XHR **from inside** a sandboxed preview is now rejected. I checked: nothing bb ships does that. The only in-app call to `/api/v1` outside the app bundle is `plugins/tasks`, which runs in the main document at the app origin. That behavior change is intended — sandboxed previews render untrusted user and agent output. **3. curl, the `bb` CLI, and the SDK.** All send no `Origin` and pass untouched. Tested directly, including a `POST` with `application/x-www-form-urlencoded` asserting it is **not** 415, so the `curl -d` path is pinned against someone turning `requireJsonForMutation` on later. The SDK is exercised end to end through `createNodeBbSdk`. ## GET side-effect audit Because a browser does not send `Origin` on a GET, a state-changing GET would slip past this guard. I enumerated all **66** GET handlers under `/api/v1/*` and checked each for mutating calls. **No GET changes durable state.** Two are worth naming: - `threads/:id/events/wait` — a bounded long-poll (≤60s) that registers a waiter and cancels it. A resource hold, not a state change, and the response is unreadable cross-origin. - `terminals/:id/output` — sends a `terminal.attach` replay RPC to the daemon. Idempotent; `sinceSeq` is caller-supplied and nothing is consumed. The rest of the flagged matches were false positives on inspection: `createDaemonFileContentResponse` builds a `Response`, and the `delete` hits are in-memory cache and lease eviction (`conversationOutlineCache`, `previewLeases`). `requireThreadCommandEnvironment` looks up an environment and never provisions one, so `GET /rate-limit-recovery` is a pure read. Nothing to fix, so nothing filed. ## Testing - `apps/server/test/security/api-origin-guard.test.ts` — 7 tests covering all four verifications above. - Salvaged with their reviewed tests from the closed #1522: the daemon local-API guard and the machine-auth proxy guards, including the rebound-`Host` test. - `pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/host-daemon --force`: **1479** server tests, **553** host-daemon tests, all passing. One unrelated pre-existing failure in this environment: `internal-skill-trees.test.ts` asserts file mode `0644` while my shell's `umask 0002` produces `0664`. It passes under `umask 022`, and touches no code in this change. Fixes #1531 > AGENT GENERATED: by Claude Opus 5 --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Accepted risk
After this change, a page on a public hostname opened in the in-app browser can reach non-bb loopback services — not only a local page can. Sawyer reviewed this and accepted it.
The bar is that the in-app browser is a browser: plain Chromium 146 with identical
webPreferencesand no bb session hardening behaves exactly the same way. Chromium applies no Local Network Access check on this path, so this change does not make bb weaker than the browser the user would otherwise use.bb's own services are not part of the residual. Layer 1 (#1536) guards
/api/v1/*, the host-daemon local API, and the machine-auth proxy against foreign browser origins, so a public page cannot drive bb itself.Reproduced in real Electron 41 (Chromium 146) under Xvfb, driving the production
createDesktopBrowserViewManagerbundled fromapps/desktop/src, with the page served from a public hostname mapped to this machine via--host-resolver-rules="MAP public.example 127.0.0.1":The permission handlers are not involved: the only permission Chromium requests on this path is
background-sync, and allowing every permission changes nothing. Details and both control runs are preserved in #1539, closed as intended behaviour.Layer 2 of 2. Prerequisite: #1536, which gives each bb service its own origin guard. That layer must land first — this one removes the blanket firewall that was standing in for those guards.
Summary
A page served from one localhost port could not open a WebSocket to a second localhost port in bb's in-app browser. The shell rendered and live data stayed pending forever, while the same URL worked in Chrome and Safari.
The cause was not a CSP, a certificate, a proxy, or a permission handler — the in-app browser has none of those. The only enforcement point was
session.webRequest.onBeforeRequest→shouldBlockBrowserRequest, which allowed a loopback subresource only back to the page's exact origin, port included.ws://127.0.0.1:3210never matched a page on:3009. Vite HMR was unaffected only because it uses the page's own port.This deletes that firewall rather than refining it. bb is local software the user controls; a page they deliberately opened reaching another local port — including bb's own server — is intended. The protection that actually belongs somewhere is a guard on each service, which is #1536.
What is deleted
From
apps/desktop/src/desktop-browser-policy.ts(491 lines → 65):shouldBlockBrowserRequestand its args typeisLoopbackBrowserRequestHost,isPrivateBrowserRequestHost,isBlockedBrowserRequestHost,isBlockedBrowserRequestUrlparseIpv4Octets,expandIpv6,isPrivateIpv6Literal, …)localRequestOriginKey,resolveRequestingFrameLocalOriginKey, and the origin-key plumbingFrom
apps/desktop/src/desktop-browser-view.ts:session.webRequest.onBeforeRequestwiringshouldBlockEntryTopLevelRequest,commitEntryMainFrameUrl,clearEntryLocalOriginState, and the entry'scurrentMainFrameLocalOriginKeyEvery test for the above is deleted too — 15 tests from the manager suite, 6
describeblocks from the policy suite, plus the now-deadbrowserRequestBlockedhelper and the fake session'swebRequestmock. No skipped tests, no commented blocks.What is kept
isAllowedBrowserUrl—file:,javascript:,data:,about:, and custom schemes still cannot be navigated to. Thewill-navigate,will-frame-navigate, andwill-redirecthandlers keep enforcing it; they just no longer consult the firewall.setWindowOpenHandleralways returningdeny— a native OS popup never opens; an allowed URL becomes an in-panel tab.clipboard-sanitized-write, downloads denied,sandbox,contextIsolation,webSecurity, no preload.One judgment call worth flagging.
resolveWindowOpenActionpreviously denied popups to loopback and LAN hosts, via the same host classification being deleted. It now allows them like any other http(s) URL. Opening a popup tolocalhost:38886is the same act as typing that address into the panel, which was always allowed — keeping the denial would have meant keeping the classifier this PR exists to remove. The scheme check and the rate limit, which are a different concern, both stay.Testing
pnpm exec turbo run typecheck test --filter=@bb/desktop --force: 212 tests passing.127.0.0.1:3009opening a socket to127.0.0.1:3210:cross-port-errorwith the firewall,cross-port-open okwithout it, and both sockets open in a plain Chromium window with identicalwebPreferences— which pinned the cancel on bb's handler rather than Chromium.Fixes #1452