Skip to content

Guard bb's local HTTP services against foreign browser origins - #1536

Merged
SawyerHood merged 3 commits into
mainfrom
sweep/api-origin-guards
Aug 13, 2026
Merged

SawyerHood merged 3 commits into
mainfrom
sweep/api-origin-guards

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Aug 13, 2026 •

Copy link
Copy Markdown
Collaborator

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 [issue sweep] Let in-app browser pages reach other loopback ports #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

@SawyerHood SawyerHood changed the title sweep/api origin guards Guard bb's local HTTP services against foreign browser origins Aug 13, 2026
@SawyerHood
SawyerHood marked this pull request as ready for review August 13, 2026 15:35
@bb-slop-cop

bb-slop-cop Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

🚨 SLOP COP 🚨 · review

I am SlopCop. I am reviewing this pull request for security, code quality, architecture, performance, and end-to-end behavior.

I will return with one final review after the parallel checks finish.

Comment thread apps/host-daemon/src/local-api.ts Outdated
origin: string,
requestUrl: string,
): Promise<boolean> =>
origin === new URL(requestUrl).origin ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The origin check trusts an attacker-controlled Host during DNS rebinding.

A DNS-rebound page sends matching Origin and Host values. This branch treats that pair as the daemon's own origin.

I sent both values as rebind.example:<daemon-port>. The request returned 200 and called openInTarget once.

Please validate Host against the bound loopback authority and port. Add a regression test with matching rebound values.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 6018b61. I reproduced it before changing anything: Origin: http://rebind.example:<port> with a matching Host returned 200 and ran the handler, exactly as you describe. The first branch of isAllowedAppOrigin compared the origin against the authority the client addressed, and a rebound page controls both halves of that comparison.

The fix takes the property that is specific to this API: it binds 127.0.0.1 (DEFAULT_HOST_DAEMON_LOCAL_BIND_HOST), so every request that reaches it arrived over loopback and a genuine caller always addresses it by a loopback name or a bare address. The self-origin branch now requires that; the configured allowlists (allowedCorsOrigins, and client-config origins) are exact matches and are untouched, so the remote-SSH client-config path still works.

Regression test added as you asked — a matching rebound Origin/Host pair gets 403 with openInTarget never called, and the loopback authority a real caller sends still gets 200. It goes over http.request, because fetch silently drops a Host override and a fetch-based version of this test would pass for the wrong reason.

Comment thread apps/server/src/server.ts
if (PLUGIN_WIRE_HTTP_PATH.test(context.req.path)) {
return next();
}
const problem = browserRequestProblem(context, deps);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 slopcop/review — The API-wide guard inherits the same DNS-rebinding bypass.

browserRequestProblem accepts Origin when it equals the request target from Host. A rebound page controls both values.

A real request used Host and Origin values for rebind.example. The request returned 200 for /api/v1/threads.

Please require an expected authority. Preserve the configured app, Connect, LAN, and Tailscale paths explicitly.

This fix must land before the firewall removal.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed as a real bypass, and I tried your fix — it breaks a deliberate, tested behavior, so I reverted it and filed instead. Worth walking through, because the outcome is not "won't fix".

First, the bypass is real. Before any change: Origin: http://rebind.example:<port> with Host: rebind.example:<port> → 200 on /api/v1/threads.

Then I implemented what you asked — require a self-evident local authority (loopback name or bare IP literal), so a public name has to be named in configuration. Rebinding was closed. But the existing suite failed:

plugin-wire.test.ts > local auth rejects foreign origins but tolerates host-bound LAN/Tailscale serving
AssertionError: expected 403 to be 200

The assertion it broke:

// Direct LAN/Tailscale serving binds the app origin to the request host.
const sameOriginReverseProxy = await harness.app.request(
  "https://bb.lan.test/api/v1/plugins/wire/http/hello",
  { headers: { origin: "https://bb.lan.test" } },
);
expect(sameOriginReverseProxy.status).toBe(200);

bb deliberately supports being served at an arbitrary DNS name bound to the request Host, with no configuration. That is the same branch you are asking me to remove, and bb.lan.test is header-indistinguishable from rebind.example: both are public names resolving to this machine, both control Origin and Host, both make them agree. No header-only rule separates them. Closing the bypass necessarily drops unconfigured DNS-name serving.

That is a product decision about supported deployment shapes, and it is bigger than this PR. Reverted, and filed with the full analysis, the reproduction, and the failing assertion so whoever takes it starts from the tradeoff rather than rediscovering it.

Two things that bound the risk in the meantime, neither of which makes it acceptable indefinitely:

  • It is pre-existing, not introduced here. browserRequestProblem has guarded /ws, /ws/terminals/:id, 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 — a rebound page could already drive every one of those routes before this PR, with nothing in the way.
  • The GET audit in this PR found no /api/v1/* GET that changes durable state, and a rebound mutation does send an Origin, so it is caught by the exact-allowlist path in the common configured cases.

On "this fix must land before the firewall removal": I disagree, and here is the reasoning. Rebinding reaches the bb server from any browser on the machine — the user's everyday Chrome included. It is not gated on bb's in-app browser, so #1537 neither enables nor worsens it. Sequencing this fix ahead of #1537 would not protect anything that is not already reachable.

What #1537 does introduce is a different gap — public pages reaching non-bb loopback services — which I verified and filed as #1539 with a merge-blocking warning on that PR.

I did fix the daemon half, where the same weakness had a clean answer: that API binds loopback, so requiring a loopback authority costs nothing. See the sibling thread.

@bb-slop-cop bb-slop-cop Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 SLOP COP 🚨 · review

ELI5: bb has three small doors on your computer. This PR adds guards to the doors. One guard trusts a name tag. A bad website can write that name tag.

I found one high-severity security gap. I posted two inline comments for the affected call sites.

Security

The host-daemon local API and the main API trust matching Origin and Host values. A DNS-rebound page controls both values.

The local API reproduction returned 200 and called openInTarget once. The main API reproduction returned 200 for /api/v1/threads.

The machine-auth proxy handles this case correctly. Its strict loopback authority check rejects a rebound Host.

Fix the daemon check in this pull request. Fix the server check before the firewall removal lands.

Architecture and duplication

Share the strict authority parser and loopback check after the security fix. The current code has similar checks in multiple packages.

The plugin-wire exemption also repeats its route path in server.ts. Export that path rule from the route owner.

The CORS callback and the request guard use different origin rules. Use one policy to prevent future drift.

Performance

I found no material performance regression. The proxy still streams request and response bodies.

The new API guard builds another origin set on each request. Precompute the stable set during createApp as a small cleanup.

Validation

  • GitHub CI passed all reported checks.
  • The host-daemon suite passed 46 files and 553 tests.
  • The focused server suite passed all seven origin-guard tests.
  • Chromium sent a foreign no-cors POST. The target handler call count stayed at zero.
  • The DNS-rebound local API reproduction returned 200 and called the target handler once.
  • This change does not alter the daemon wire contract. It does not need a protocol version change.

I posted a comment-only review. I did not approve or request changes.

SawyerHood and others added 3 commits August 13, 2026 16:14
CORS decides whether a browser may read a response; it never stops the
request. A no-cors POST with a simple content type skips the preflight, 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.

Three services now reject a foreign browser origin outright:

- The server's /api/v1/*, which had cors() but no rejecting guard. Only /ws,
  the plugin routes, and the file routes called browserRequestProblem.
  Excluded: /api/v1/plugins/<id>/http/*, where the plugin declares its own
  auth mode and `none` is deliberately public.
- The host daemon's local API, which computed an allow predicate for CORS but
  never rejected on it.
- The machine-auth proxy, which stamps a machine credential onto everything it
  forwards. Origin and Sec-Fetch-Site catch a browser; a Host authority check
  catches a DNS-rebound public name, which sends neither.

requireJsonForMutation is deliberately NOT set on /api/v1/*: it answers 415 to
a mutation without application/json and would break every 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: Node's own fetch sends
sec-fetch-mode: cors, so keying on it would reject the runtime processes the
proxy exists to serve.

Fixes #1531

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The local API trusted an origin that matched the authority the client
addressed. A page on a public name that resolves to this machine controls both
Origin and Host, so it can make them agree; SlopCop confirmed a rebound pair
reached /open-in-target. This API binds 127.0.0.1, so a genuine caller always
addresses it by a loopback name or a bare address — require that of the
self-origin branch. Configured client and app origins are exact allowlists and
are unaffected.

Also pins the callers a blanket origin guard could lock out: LAN and Tailscale
serving, a rewriting proxy that forwards X-Forwarded-Host, and the one shape
that does not work (a rewriting proxy that forwards nothing). These go over
http.request because fetch silently drops a Host override, so a fetch-based
version of the test would pass for the wrong reason.

The same rebinding weakness in the server's browserRequestProblem is NOT
fixed here: bb deliberately supports being served at an arbitrary DNS name
bound to the request Host, which plugin-wire asserts, and that shape is
header-indistinguishable from a rebound one. Filed separately.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The test hardcoded 127.0.0.1 while the harness binds "localhost", which
resolves to ::1 on the CI runner — so the connection was refused there while
passing locally. Use the server's reported bindHost for both the connection
and the loopback Host header.

Verified under --dns-result-order=ipv6first as well as the default.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@SawyerHood
SawyerHood force-pushed the sweep/api-origin-guards branch from d713e65 to 0357cb8 Compare August 13, 2026 16:15
@SawyerHood
SawyerHood merged commit c34eabb into main Aug 13, 2026
10 checks passed
@SawyerHood
SawyerHood deleted the sweep/api-origin-guards branch August 13, 2026 16:25
SawyerHood added a commit that referenced this pull request Aug 13, 2026
## 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 `webPreferences` and 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 `createDesktopBrowserViewManager` bundled from
`apps/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"`:

```
### bb manager (this PR), page on PUBLIC hostname
[backend] WS ACCEPTED
[backend] HTTP REACHED

### plain Chromium, same page, no bb hardening   <- the control
[backend] WS ACCEPTED
[backend] HTTP REACHED
```

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:3210` never 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):

- `shouldBlockBrowserRequest` and its args type
- `isLoopbackBrowserRequestHost`, `isPrivateBrowserRequestHost`,
`isBlockedBrowserRequestHost`, `isBlockedBrowserRequestUrl`
- the IPv4/IPv6 classification helpers (`parseIpv4Octets`, `expandIpv6`,
`isPrivateIpv6Literal`, …)
- `localRequestOriginKey`, `resolveRequestingFrameLocalOriginKey`, and
the origin-key plumbing

From `apps/desktop/src/desktop-browser-view.ts`:

- the `session.webRequest.onBeforeRequest` wiring
- `shouldBlockEntryTopLevelRequest`, `commitEntryMainFrameUrl`,
`clearEntryLocalOriginState`, and the entry's
`currentMainFrameLocalOriginKey`

Every test for the above is deleted too — 15 tests from the manager
suite, 6 `describe` blocks from the policy suite, plus the now-dead
`browserRequestBlocked` helper and the fake session's `webRequest` mock.
No skipped tests, no commented blocks.

## What is kept

- **`isAllowedBrowserUrl`** — `file:`, `javascript:`, `data:`, `about:`,
and custom schemes still cannot be navigated to. The `will-navigate`,
`will-frame-navigate`, and `will-redirect` handlers keep enforcing it;
they just no longer consult the firewall.
- **The popup rate limit** — 3 popup-to-tab conversions per 10s, so a
hostile page cannot flood the panel.
- **`setWindowOpenHandler` always returning `deny`** — a native OS popup
never opens; an allowed URL becomes an in-panel tab.
- Everything else in the session hardening: permissions denied except
`clipboard-sanitized-write`, downloads denied, `sandbox`,
`contextIsolation`, `webSecurity`, no preload.

**One judgment call worth flagging.** `resolveWindowOpenAction`
previously 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 to `localhost:38886` is 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.
- The full stack re-verified together: 212 desktop, 1479 server, 553
host-daemon.
- The original fault was reproduced before this work in real Electron
under Xvfb, driving the production view manager against a page on
`127.0.0.1:3009` opening a socket to `127.0.0.1:3210`:
`cross-port-error` with the firewall, `cross-port-open ok` without it,
and both sockets open in a plain Chromium window with identical
`webPreferences` — which pinned the cancel on bb's handler rather than
Chromium.

Fixes #1452

> AGENT GENERATED: by Claude Opus 5

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Loopback services with no browser-origin guard: /api/v1, second bb server, mock CLI traffic proxy

1 participant