Repository navigation
[issue sweep] Let in-app browser pages reach other loopback ports - #1522
SawyerHood wants to merge 5 commits into
Conversation
The in-app browser firewall allowed a loopback page to make subresource, fetch, and WebSocket requests only to its own exact origin, port included. A local app whose frontend and WebSocket backend sit on different loopback ports therefore never connected, and its live data stayed pending forever. Vite HMR was unaffected because it uses the page's own port. The firewall exists to keep browsed pages away from bb's own loopback services and from the user's LAN. Name those bb ports instead: the local bb server and the host-daemon local API. Every other loopback port is now reachable from a committed loopback page, as it is in Chrome and Safari. Remote origins still reach no loopback port, and private/LAN hosts stay blocked. Fixes #1452 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚨 SLOP COP 🚨 · I am the Slop Cop. I am reviewing this change for security, code quality, architecture, duplicate code, performance, and end-to-end behavior. |
The daemon port arrived only with the first system-config fetch, and the config sync clears it on stop. A browsed page opened in that window reached the host daemon's local API. Reserve the packaged constant unconditionally and keep the fetched value for dev instances. The assembly moves into `resolveReservedLoopbackPorts`, a pure function, so the startup window is covered by a test. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| if (token !== systemConfigRefreshToken) { | ||
| return; | ||
| } | ||
| currentLocalHostDaemonPort = |
There was a problem hiding this comment.
🚨 slopcop/review — A remote target removes protection from the active local daemon
A remote config response sets this value to null. However, the target switch does not stop currentRuntime. The local daemon can remain active while its port leaves the reserved list. A local page can then send a blind no-cors request to /open-in-target. Keep the local daemon port until the local runtime stops. Do not connect this host-local state to the selected remote config.
There was a problem hiding this comment.
Confirmed and fixed in f631d8a.
I traced the switch: setActiveServerTarget → the connect/custom branches call startRemoteSystemConfigSync and never stopOwnedRuntime, so currentRuntime and its daemon stay up. refreshSystemConfig then ran with the remote URL and nulled the port.
Only a loopback server now writes the value, and nothing else clears it:
if (loopbackServicePort(args.serverUrl) !== null) {
currentLocalHostDaemonPort = config.hostDaemonPort;
}Clearing stays in stopSystemConfigSync, whose only callers are setCurrentRuntime(null) and finishQuit — the local runtime stopping and the app quitting, exactly as you asked. Covered by keeps the local daemon port reserved while pointed at a remote server.
| // A committed loopback page reaching a second loopback port is ordinary local | ||
| // development, so it is allowed here as it is in Chrome and Safari. bb's own | ||
| // loopback services stay unreachable, which is what this firewall protects. | ||
| return args.reservedLoopbackPorts.includes(effectiveRequestPort(parsed)); |
There was a problem hiding this comment.
🚨 slopcop/review — An unlisted credential proxy becomes reachable
This rule allows every unreserved loopback port. The host daemon also opens a random machine-auth proxy port that this list cannot include. That proxy adds x-bb-connect-machine to forwarded requests. A local page can send blind no-cors POST requests with text/plain JSON. CORS hides the response, but it does not stop the action. Please reject browser-origin requests at the proxy, require a secret URL token, or reserve the actual proxy port as another control.
There was a problem hiding this comment.
Confirmed, and the most serious of the three. Fixed in f631d8a by rejecting browser-originated requests at the proxy — your first suggested control. The port is chosen with server.listen(options.port ?? 0, ...) inside the daemon, so no reserved list the desktop assembles can ever name it.
I verified the exposure is real rather than theoretical. In the same real-Electron harness, a page on 127.0.0.1:3009 fired blind no-cors probes at an unreserved loopback port:
[proxy-stand-in] GET guard=REJECT via=sec-fetch-site
[proxy-stand-in] POST guard=REJECT via=origin,sec-fetch-site
Both reached the port and both are caught by the guard.
One correction to the header set, which my own test caught before I pushed: Sec-Fetch-Mode is not a discriminator. Node's fetch sends sec-fetch-mode: cors, so including it rejected the runtime processes this proxy exists to serve — three existing proxy tests went red. The guard keys on Origin and Sec-Fetch-Site only. Origin covers writes and WebSocket handshakes; Sec-Fetch-Site covers the blind no-cors GET that carries no Origin. Node sends neither, which the test asserts directly.
This is the same reasoning the server already uses in browser-request-guard.ts. No HOST_DAEMON_PROTOCOL_VERSION bump: the proxy is a local endpoint for spawned runtime processes, not the server↔daemon channel, and no field on that channel changed.
Covered by rejects browser-originated requests without reaching upstream and rejects a browser WebSocket handshake without reaching upstream.
| */ | ||
| function reservedLoopbackPorts(): readonly number[] { | ||
| const ports = new Set<number>(); | ||
| for (const serverUrl of [builtinServerUrl, currentRuntime?.serverUrl]) { |
There was a problem hiding this comment.
🚨 slopcop/review — The active desktop Vite port is absent
Development mode loads BB from a separate loopback Vite port. This list includes only server URLs and the known daemon port. The new cross-port rule lets another local page reach that BB-owned Vite service. Please include a loopback BB_DESKTOP_APP_URL port when it is active. Also test the production list assembly and target transitions.
There was a problem hiding this comment.
Confirmed and fixed in f631d8a. resolveReservedLoopbackPorts now takes appWindowUrl and reserves its port, fed from currentWindowUrl — the URL loadWindowUrl actually committed. That covers the dev Vite server (BB_DESKTOP_APP_URL) and is a no-op in production, where the app window is the server URL already in the list, and for a remote target, where the URL is not loopback.
Reading currentWindowUrl rather than the env var means the reserved port follows what the window really loaded, including after a target switch.
Both requests are tested: reserves the loopback app-window port in dev covers the dev assembly, and keeps the local daemon port reserved while pointed at a remote server covers the target transition, asserting the exact set so a silently dropped port fails. Production assembly is covered by reserves the packaged host-daemon port before any port is fetched.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: BB now lets a local webpage talk to related local servers. The safety list misses two BB services. It also loses one protected port after a server switch.
I found three concrete regressions.
-
High — The random machine-auth proxy becomes reachable. The daemon opens an unlisted loopback proxy and adds a machine credential to forwarded requests. A local page can send blind
no-corsPOST requests through it. CORS does not stop the request. -
Medium — A remote target drops the active local daemon port. The local runtime can remain active after a target switch. The remote config then clears its daemon port from the reserved list. A local page can reach
/open-in-targetwithtext/plainJSON. -
Low — The desktop Vite port is absent. Development mode uses a separate BB-owned loopback port. The new rule allows other local pages to reach it.
The clean architecture is one active loopback-listener registry. The runtime should own that registry. The request policy should read one complete set. The startup probe already parses the daemon port and then discards it. Keep that value instead of a second asynchronous config path. Add tests for the proxy port, the Vite port, startup, remote target changes, and inactive ports.
I found no material performance regression. The request path rebuilds a very small list. A later change can cache an immutable set when runtime state changes.
The documented DNS rebinding gap existed before this pull request. I did not count it as a new finding.
Validation passed on exact SHA 96a478747a79662c55288f5f9c41d293f4ececc8:
- Desktop tests: 32 files and 237 tests passed.
- The desktop Turbo type check passed.
git diff --checkpassed.- The focused policy suites passed all 71 tests.
I could not complete a live dev-browser test. This behavior runs inside Electron session.webRequest, which a normal web dev server cannot exercise. The manager-level request filter tests passed.
If a new daemon wire field reports the proxy port, increment HOST_DAEMON_PROTOCOL_VERSION.
Three gaps in the relaxed firewall: A remote target set the local daemon port to null while the local runtime, and its daemon, kept running. Only a loopback server now writes that port, and only the local runtime stopping clears it. The dev bb app window loads from a loopback Vite server bb owns, which no server URL or daemon port named. Reserve the app window URL's port. The host daemon's machine-auth proxy takes a random loopback port that no reserved list can name, and it stamps every forwarded request with a machine credential. A browsed page could reach it and act through a blind no-cors request whose response CORS hides. Reject browser-originated requests at the proxy instead. `Origin` covers writes and WebSocket handshakes; `Sec-Fetch-Site` covers a no-cors GET that sends no `Origin`. `Sec-Fetch-Mode` is deliberately not used: Node's own fetch sends it, so it would reject the runtime processes the proxy exists to serve. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚨 SLOP COP 🚨 · I am SlopCop. I am reviewing this pull request for security, code quality, performance, architecture, and end-to-end behavior. |
| * and a `no-cors` request still acts even though its response stays hidden, so | ||
| * a browsed page must never borrow that credential. | ||
| */ | ||
| export function isBrowserRequest(headers: IncomingHttpHeaders): boolean { |
There was a problem hiding this comment.
🚨 slopcop/review — Block non-loopback Host values before the proxy adds the machine credential.
This check treats missing browser headers as proof of a trusted caller. A DNS-rebound page can use a public hostname that resolves to 127.0.0.1. For an HTTP GET, the browser can omit both checked headers. The desktop firewall also sees the public hostname and permits the request. The proxy then adds x-bb-connect-machine. I reproduced this with Host: rebind.example:<proxy-port> and no checked headers. The upstream received the request and the machine credential. Validate the incoming Host against the proxy loopback authority. An unguessable capability in the proxy URL would give stronger protection.
There was a problem hiding this comment.
Confirmed and fixed in 961476c. Your reproduction is right, and I reproduced it independently in real Electron against the production browser-view manager using --host-resolver-rules="MAP rebind.example 127.0.0.1":
[proxy-stand-in] GET host=rebind.example:41999 guard=ALLOW via=none
Neither checked header is present. The reason is worth recording: http://rebind.example is not a potentially trustworthy URL, so Chromium omits Sec-Fetch-* entirely, and a no-cors GET omits Origin. A rebound request is header-identical to a local Node process, so isBrowserRequest structurally cannot see it. The direct-loopback probes in the same run still carry the headers, which is why both checks are needed rather than either alone.
The proxy now also requires the request Host to be its own loopback authority — 127.0.0.1, localhost, or [::1] on the bound port, read at request time so it matches the port actually bound rather than the requested one. A rebound request carries the public name and is rejected.
Verified end to end against the real proxy (bundled from apps/host-daemon/src, fronting a fake upstream that logs the credential):
[node-client] status=200
[upstream] REACHED POST /api/v1/threads credential=bbcm_repro
with no [upstream] REACHED line for any of the three browser probes — direct GET, direct POST, and rebound GET. The Node control proves the proxy still serves its real callers rather than the harness being broken.
On the capability token: I agree it is the stronger control, and it is the one thing here I have not done. It changes what BB_SERVER_URL hands every runtime process, which is a wider blast radius than this PR should carry. Filed as #1530 along with the general DNS-rebinding residual in the desktop firewall, which this PR does not introduce — that branch already allowed public hostnames before the change — and which remains open for every other loopback service.
Covered by rejects a rebound public Host without reaching upstream, which also asserts a mismatched port and the three authorities a real client sends.
| export function resolveReservedLoopbackPorts( | ||
| args: ResolveReservedLoopbackPortsArgs, | ||
| ): readonly number[] { | ||
| const ports = new Set<number>([BB_PROD_HOST_DAEMON_PORT]); |
There was a problem hiding this comment.
🚨 slopcop/review — Keep cross-port access closed until the local daemon port is known.
The initial set reserves only port 38887. The development app uses another daemon port. A configured production app can also use another port. The app loads restored browser tabs before the first asynchronous system-config response sets currentLocalHostDaemonPort. During this interval, a local page can reach the real daemon port. The interval stays open if the fetch fails. Reserve the validated BB_HOST_DAEMON_PORT value before browser views exist. Also keep cross-port access closed until the local config is complete. Add a test for a non-default daemon port with a pending config fetch.
There was a problem hiding this comment.
Confirmed and fixed in 961476c, both halves.
Reserve the configured port. BB_HOST_DAEMON_PORT is set for every dev instance — toDevProcessEnv writes it at packages/config/src/runtime.ts:333, and run-electron-dev.mjs passes that env to Electron — and for a configured production deployment. resolveReservedLoopbackPorts now parses it directly, so the real daemon port is named before any fetch. An unusable value (empty, 0, 70000, non-numeric) is treated as unknown rather than silently reserving something wrong.
Stay closed until the config is complete. Reserving is not enough on its own, because you are right that the fetch can simply never succeed. ReservedLoopbackPorts is now a union:
export type ReservedLoopbackPorts =
| { kind: "known"; ports: readonly number[] }
| { kind: "pending" };pending when a local runtime is up whose daemon port is neither configured nor fetched, and shouldBlockBrowserRequest blocks every cross-port loopback target while pending. Same-origin subresources keep working throughout, so a restored tab still renders — it just cannot reach a second port until bb can name its own. A failed fetch now fails closed instead of leaving the window open indefinitely.
Tests, as requested — a non-default daemon port with a pending fetch is the first one:
stays pending while a local runtime's daemon port is unknown— local server on 19123, no configured port, no fetched port.names a configured daemon port without waiting for the fetch.treats an unusable BB_HOST_DAEMON_PORT as unknown.blocks cross-port loopback while bb cannot name its own ports— through the realonBeforeRequestwiring, asserting same-origin still passes.
One limit I want to state rather than leave implied: if the desktop has no local runtime but the user separately runs a bb dev instance, that instance's ports are outside anything this process can observe. The packaged and configured defaults are the best available signal there.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: The in-app browser can now connect two parts of one local app. It still tries to protect bb services.
I found two security gaps.
- High: DNS rebinding can bypass the new machine-proxy browser check. A public Host reached upstream and received the machine credential in my reproduction. Validate the exact loopback Host. Prefer an unguessable proxy capability.
- Medium: A non-default daemon port stays open before the first local config response. Reserve the environment port before browser views exist. Keep cross-port access closed until local config is complete.
The architecture search found duplicate host and IP parsing in the desktop policy and apps/app/src/lib/browser-url.ts. A shared parser could reduce policy drift. Keep the different product decisions in their current owners.
I found no material performance problem. The new reserved-port calculation measured about 2.85 microseconds per request. HTTP bodies and WebSocket traffic still use streams. Socket cleanup worked in the tested rejection paths.
I tested the exact head in a real Electron 41 app. A cross-port fetch and WebSocket both succeeded. Requests to the active bb server and daemon ports both failed.
Local checks passed:
- 241 desktop tests.
- 547 host-daemon tests.
- Desktop and host-daemon type checks.
git diff --check.
I did not approve the pull request or request changes.
Two further gaps the second review pass found. The machine-auth proxy's header check treated a missing Origin and Sec-Fetch-Site as proof of a trusted caller. A page on a public hostname that DNS-rebinds to 127.0.0.1 sends neither: `http://rebind.example` is not a potentially trustworthy URL, so Chromium omits Sec-Fetch-*, and a no-cors GET omits Origin. Verified in Electron with `--host-resolver-rules="MAP rebind.example 127.0.0.1"`. The proxy now also requires the request's Host to be its own loopback authority. The reserved-port set named only the packaged daemon port until the first system-config fetch landed, and that fetch can fail. Cross-port loopback now stays closed while a local runtime is up whose daemon port bb cannot name, and BB_HOST_DAEMON_PORT is read directly, which is set for every dev instance and for a configured production deployment. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚨 SLOP COP 🚨 · I am SlopCop. I am reviewing this pull request now. I will check security, code quality, architecture, performance, and the end-to-end route. Three parallel reviewers will inspect the change. A final reviewer will check the combined result. |
| if (args.reservedLoopbackPorts.kind === "pending") { | ||
| return true; | ||
| } | ||
| return args.reservedLoopbackPorts.ports.includes( |
There was a problem hiding this comment.
🚨 slopcop/review — An extra daemon stays outside this reserved list.
BB supports an extra host daemon on a distinct port. Its full local API has no authentication.
A simple text/plain JSON request can call /open-in-target. The old policy blocked that cross-port request.
This rule allows the request because the extra port is absent. Guard each full local API against foreign browser origins.
A complete active-listener set could also close this gap.
There was a problem hiding this comment.
Confirmed and fixed in 651b4ff. This one is a genuine regression from my change — the old exact-origin rule blocked the cross-port request, and relaxing it opened the route.
I checked the claim rather than taking it: startLocalApiServer passes an allow predicate to cors({ origin }), but that callback only decides whether to echo Access-Control-Allow-Origin. It never rejects. A no-cors POST with content-type: text/plain is a CORS-simple request, so no preflight guards it, and c.req.json() parses the body regardless of the header — the handler runs and the page simply never reads the reply. A second daemon (a dev instance alongside the packaged app) sits on a port the desktop cannot enumerate, so no reserved list closes this.
The fix is your first suggestion: the same predicate the CORS callback already computed is now enforced as a request guard, rejecting a present-but-foreign Origin with 403 before any handler runs. /health stays exempt, and a caller sending no Origin — every non-browser caller — is unaffected. This matches what the bb server already does in browser-request-guard.ts.
I confirmed the test actually protects the bug rather than passing by construction. With the guard disabled:
AssertionError: expected 200 to be 403
The blind POST reaches the handler. With it enabled, 403 and openInTarget is never called. The test also covers a DNS-rebound origin (http://rebind.example → 403) and asserts the bb app's own origin and a no-Origin caller still succeed.
On your second suggestion, a complete active-listener set: I did not take it. The desktop cannot enumerate every bb daemon on the machine — a second instance is started outside its process and reports its port to nobody — so any such set would be incomplete in exactly the case that matters, and would read as covering more than it does. Guarding each service is the control that actually holds. #1530 tracks the remaining shape of this, including the unguessable-capability idea.
No HOST_DAEMON_PROTOCOL_VERSION bump: no field on the server↔daemon channel changed, and the requests now rejected were never legitimate, so an older bb app frontend sending an allowed origin is unaffected.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5: BB now lets one local app contact another local port. An extra BB helper can use a different port.
High security finding
BB supports extra host daemons on distinct ports. The reserved set names only one daemon and the fixed default ports.
Each daemon starts a full local API without authentication. CORS does not stop simple requests.
A safe probe sent text/plain JSON from another loopback origin. The API returned 200 and called the native action handler.
This PR now lets that page reach the extra daemon directly. The old policy blocked this cross-port route.
The same root can lose one saved daemon port after a second local target replaces it. The first local runtime remains active.
Protect every full local API with authority and browser-origin checks. A complete active-listener set is another option.
Other results
The general DNS rebinding gap existed before this PR. Issue #1530 tracks it, so I did not count it again.
The architecture scan found duplicate loopback classifiers and effective-port helpers. A shared parser is useful, but it is not required here.
I found no material performance issue. The reserved-port calculation averaged 1.483 microseconds across one million calls.
A real Electron test passed the intended route. Cross-port HTTP and WebSocket requests worked, while named BB ports stayed blocked.
The random machine-auth proxy rejected 500 browser requests. It also rejected a browser WebSocket, but allowed the expected Node request.
Twenty temporary browser views closed correctly. The target count returned to one.
Validation
- Desktop tests passed: 245 tests.
- Host-daemon tests passed: 548 tests.
- Both Turbo type checks passed.
- GitHub CI passed.
git diff --checkpassed.- The worktree stayed clean at the requested SHA.
The final GPT-5.6 gate returned REQUEST CHANGES. I posted only a comment review, as required.
A second bb daemon on this machine sits on a port the desktop cannot name, so the relaxed firewall lets a browsed page reach its local API. The API set CORS headers but never rejected the request, and CORS only hides a response: a no-cors POST with a simple content type skips the preflight, reaches /open-in-target, and runs it while the page never reads the reply. The allow predicate the CORS callback already computed is now enforced as a request guard. A caller sending no Origin, which is every non-browser caller, is unaffected. Verified the test fails without the guard: the blind POST returns 200. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
|
🚨 SLOP COP 🚨 · I am SlopCop. I am reviewing this pull request now. I will check security, code quality, performance, architecture, and the full product route. I will post one final review after the parallel checks finish. |
| if (args.reservedLoopbackPorts.kind === "pending") { | ||
| return true; | ||
| } | ||
| return args.reservedLoopbackPorts.ports.includes( |
There was a problem hiding this comment.
🚨 slopcop/review — A second bb server remains reachable.
This rule permits all loopback ports outside the reserved list. The desktop cannot know the port of another bb instance.
That server uses CORS for most /api/v1 routes. CORS hides the response, but it does not stop a simple request.
A local page can send a blind no-cors POST with text/plain JSON. The route parser accepts that body and can change server state.
The old exact-origin rule blocked this request. Please add the server-wide browser request guard before this cross-port rule ships.
Issue #1531 records the same blocker.
There was a problem hiding this comment.
Agreed, and we converged independently. I found this while building the loopback coverage table for the PR body, before this pass ran, and it is already recorded as a hard blocker in two places:
- A
[!CAUTION]block at the very top of this PR body: do not merge before the/api/v1/*guard in Loopback services with no browser-origin guard: /api/v1, second bb server, mock CLI traffic proxy #1531 lands. - Loopback services with no browser-origin guard: /api/v1, second bb server, mock CLI traffic proxy #1531, retitled to say it blocks [issue sweep] Let in-app browser pages reach other loopback ports #1522, with the coverage table copied in so the blocker survives any edit here.
Your diagnosis matches mine exactly: browserRequestProblem is applied to /ws, /ws/terminals/:id, and routes in plugins.ts and files.ts, but /api/v1/* has only cors(), which decides whether to echo Access-Control-Allow-Origin and never rejects. The typed route parser reads the body with c.req.json() regardless of content type, so a no-cors text/plain POST is acted on. It affects a second instance only — the attached one's port is reserved — and the old exact-origin rule blocked it, so it is a regression from this change.
I have deliberately not applied the guard in this PR. /api/v1/* is every API route, and the connect-tunnel and public-share paths cannot be verified from this PR's test surface: isTrustedOrigin should admit them through its request-Host branch, but "should" is not a basis for a global guard on every route. Landing it as its own change, with the two-server regression test you ask for, is the right shape. That is what #1531 specifies.
So: this PR does not merge until #1531 lands. That is stated at the top of the body rather than left to a reviewer to infer.
There was a problem hiding this comment.
🚨 SLOP COP 🚨 · review
ELI5
This change opens a door between two local tools. It keeps the known bb doors closed.
However, it can miss another bb door on a different port. A local page can then make that bb server do work.
Finding
I found one blocking security regression.
The new rule permits every loopback port outside its reserved list. The desktop cannot list ports from a second bb instance.
Most /api/v1 routes on that second server use CORS only. CORS hides responses, but it does not stop simple requests.
The typed route parser accepts JSON from a text/plain body. A local page can send a blind request and change server state.
The old exact-origin rule blocked this path. Issue #1531 also marks this gap as a blocker for this pull request.
Please apply the existing browserRequestProblem guard across /api/v1/*. Add a two-server regression test before this change ships.
Other notes
I found no material performance problem. The request policy cost was about 3.7 microseconds per call in a direct test.
The new origin and authority checks repeat similar code in three services. A small shared browser-boundary module can remove this duplication.
The DNS rebinding test does not change the request Host. Thus, it does not model a real DNS rebound request.
Issue #1530 already tracks that older weakness. I did not count it as a new defect in this pull request.
No server-daemon message contract changed. This pull request does not need a daemon protocol version increase.
Validation
The Electron end-to-end test passed. HTTP and WebSocket requests reached another loopback port.
The same test blocked the active bb server and host daemon ports.
The desktop test suite passed 245 tests. The host-daemon suite passed 549 tests.
Both focused type checks passed. All current GitHub checks also passed.
I am leaving a comment-only review, as required. I did not approve or request changes through GitHub.
|
Answering the three "Other notes" from Duplicated origin/authority checks across three services — agreed, and it is a prerequisite, not just cleanup. The DNS-rebinding test does not change the request const request = http.request({
host: proxyUrl.hostname, // same socket every time
port: proxyUrl.port,
path: "/api/v1/threads",
headers: { host }, // the only thing that varies
}, ...);The assertions are what prove it: What it does not model is the resolution step, which is deliberate — a unit test cannot rebind DNS. That half is covered in real Chromium instead, with which is what established that Chromium omits No daemon protocol version bump needed — agreed, and for the same reason: no field on the server↔daemon channel changed. The local-API and proxy guards reject requests that were never legitimate, so an older bb app frontend sending an allowed origin is unaffected.
|
|
Closing in favour of a two-layer stack that takes the opposite approach. The premise of this pull request was wrong. It kept the in-app browser firewall and relaxed it carefully. Four review passes then found five services the old exact-origin rule had been protecting by accident, and each fix uncovered another. That pattern is the signal: policing the browser cannot enumerate what it must protect, because a second bb instance starts outside the desktop process and reports its ports to nobody. The replacement guards each service at its own listener and then deletes the browser firewall entirely:
The in-app browser is local software the user controls, and reaching a loopback port is intended behaviour, as it is in Chrome and Safari. The work here is not wasted. The service guards and the coverage table move into layer 1, and the branch stays available.
|
**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]>
Caution
DO NOT MERGE before the
/api/v1/*origin guard in #1531 lands.This change makes a second bb server's REST API reachable from a browsed page, and nothing rejects the request.
apps/server/src/server.tsappliesbrowserRequestProblemto/ws,/ws/terminals/:id, and routes inplugins.tsandfiles.ts, but/api/v1/*has onlycors()— which decides whether to echoAccess-Control-Allow-Originand never rejects. Ano-corsPOST withcontent-type: text/plainskips the preflight and the handler runs.The attached instance's port is reserved and is not affected. The hole is a second instance — a dev instance running alongside the packaged app, which is the everyday bb-developer setup — whose port no reserved list can name. Before this change the exact-origin rule blocked that cross-port request outright, so this is a regression introduced here.
It is not fixed in this PR deliberately:
/api/v1/*touches every API route and has connect-tunnel and public-share paths that cannot be verified from this PR's test surface. Guessing there would be worse than a clear blocker. See the coverage table below and #1531.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 page shell loaded, but live data stayed pending forever. The same URL worked in Chrome and Safari.
Cause. It is not a CSP, a certificate, a proxy, or a permission handler. The in-app browser has no CSP injection and no proxy. The single enforcement point is
session.webRequest.onBeforeRequestinapps/desktop/src/desktop-browser-view.ts, which callsshouldBlockBrowserRequest. For any non-main-frame request to a loopback host, that function required the target's local-origin key to equal the committed main frame's key exactly. The key includes the port (local|127.0.0.1|3009), sows://127.0.0.1:3210never matchedhttp://127.0.0.1:3009and Chromium cancelled the handshake. Vite HMR was unaffected because it uses the page's own port.Fix. The firewall exists to keep browsed pages away from bb's own loopback services and from the user's LAN. This change names those bb ports instead of guessing them from the page's port:
shouldBlockBrowserRequesttakesreservedLoopbackPorts. A committed loopback page may now reach other loopback ports, except the reserved ones.resolveReservedLoopbackPortsassembles that list: the packaged host-daemon port always, plus the local bb server port and the host-daemon port the attached server reports. The reported daemon port is recorded only when the attached server runs on this machine's loopback, because a remote server reports its own machine's port.Trade-off a reader should not have to work out. A user's own service on a reserved port is now unreachable from the in-app browser. The packaged ports (38886, 38887) are held back even when no bb server is listening on them. That is the correct trade: a browsed page reaching bb is far worse than a browsed page missing one port.
Nothing else moves.
webSecurity,sandbox,contextIsolation, andallowRunningInsecureContentare untouched. The permission handlers are untouched. Remote origins still reach no loopback port: a page whose main frame is not loopback has a null local-origin key and is blocked before the port check. Private and LAN hosts stay blocked outright.Found by audit, not by review. The second commit closes a gap I found auditing my own change, before Slop Cop reported:
currentLocalHostDaemonPortwas populated only by the first successful/api/v1/system/configfetch and cleared bystopSystemConfigSync, so the host daemon's local API was unreserved during that window. Reserving the packaged constant unconditionally closes it, and the assembly moved into a pure function so the window is covered by a test.Review findings. Slop Cop found three ways the relaxed firewall still let a page reach bb. All three were confirmed in the code and fixed:
nullwhile the local runtime and its daemon kept running (setActiveServerTargetnever stops the runtime). Only a loopback server now writes that port, and only the local runtime stopping clears it.resolveReservedLoopbackPortsnow reserves the app window URL's port.no-corsrequest whose response CORS hides. The proxy now rejects browser-originated requests:Origincovers writes and WebSocket handshakes,Sec-Fetch-Sitecovers theno-corsGET that sends noOrigin.Sec-Fetch-Modeis deliberately excluded — Node's ownfetchsends it, so keying on it rejected the runtime processes the proxy exists to serve. NoHOST_DAEMON_PROTOCOL_VERSIONbump: the proxy is a local endpoint for spawned runtime processes, not the server↔daemon channel, and no field on that channel changed.Second review pass. A forced re-review of the pushed SHA found two more, both confirmed and fixed:
OriginandSec-Fetch-Siteas proof of a trusted caller. A page on a public hostname that DNS-rebinds to127.0.0.1sends neither, becausehttp://rebind.exampleis not a potentially trustworthy URL — so Chromium omitsSec-Fetch-*, and ano-corsGET omitsOrigin. The proxy now also requires the request'sHostto be its own loopback authority.ReservedLoopbackPortsis nowknown | pending; cross-port loopback stays closed while a local runtime is up whose daemon port bb cannot name, andBB_HOST_DAEMON_PORTis read directly (set for every dev instance and for a configured production deployment). Same-origin subresources keep working while pending, so a restored tab still renders.Third review pass. One more, confirmed and fixed: a second bb daemon on the machine (a dev instance alongside the packaged app) sits on a port the desktop cannot enumerate, and its local API only set CORS headers rather than rejecting. A
no-corsPOST with a simple content type skips the preflight and runs/open-in-targetwhile the page never reads the reply. The allow predicate the CORS callback already computed is now enforced as a request guard. This one is a genuine regression from the relaxation, since the old exact-origin rule blocked the cross-port request outright.Not fixed here, filed as #1530. The desktop firewall classifies the URL host, not the resolved address, so a public name resolving to loopback bypasses it for every loopback service. That branch already allowed public hostnames before this change, so it is not a regression from it. #1530 also carries SlopCop's stronger suggestion of an unguessable capability in the proxy URL, which changes what
BB_SERVER_URLhands every runtime process and is a wider blast radius than this PR should carry.Loopback service coverage
Three review passes each found another service the old exact-origin rule protected by accident. Rather than wait for a fourth, here is every loopback listener a bb machine can run, found by searching for listeners (
.listen(,serve(,createServer() acrossapps/,packages/, andplugins/rather than from memory.apps/server/src/start-server.tsbuiltinServerUrl, attached runtime URL). Plus anOrigincheck on/wsand/ws/terminals/:id.apps/host-daemon/src/local-api.tsBB_HOST_DAEMON_PORT, fetched value), and anOriginallowlist enforced as a request guard (this PR).apps/host-daemon/src/machine-auth-proxy.tsOrigin+Sec-Fetch-Sitecheck and aHostauthority check (this PR). Injects a machine credential, so this is the highest-authority service on the list.packages/agent-runtime/src/acp/bridge/bridge.tsbridge.ts:282), on a newline-JSON protocol an HTTP request cannot satisfy. This is the capability-token control SlopCop recommended, already in place here.apps/app/vite.dev.config.tsappWindowUrl(this PR), when it is the window the desktop loaded./api/v1/*hascors()but no request-rejecting origin guard. Filed as #1531.packages/agent-runtime/src/claude-code/bridge/mock-cli-traffic-proxy.tsrewriteHeadersforwards only what the caller sent), so it carries no ambient authority. Off by default behind theclaudeCodeMockCliTrafficexperiment. Filed as #1531.Originguard added in this PR, which is per-service and so covers every instance.What could not be enumerated. Any second bb instance: it is started outside the desktop process and reports its ports to nobody, so no reserved list can name it. That is precisely why the services themselves are guarded rather than their ports listed — a guard covers every instance, a port list covers one. The two rows above with no control are the gap that remains, both filed as #1531 with the reason each was too wide for this PR.
Not included:
apps/connect/scripts/spike-origin.mts,apps/desktop/scripts/smoke-packaged-app.mjs,packages/bb-app/scripts/smoke-tarball.mjs,scripts/bb-cloud-dev.mjs, andpackages/scripts/src/commands/run-dev.ts(which binds only to probe a port, then closes). None run as part of a user's bb.Should this have been two pull requests?
Yes — service guards first, the firewall relaxation second. Recording the assessment rather than splitting now, since splitting mid-review restarts the review passes that produced the guards.
The case for splitting is that the two halves have different revert semantics. The guards stand on their own: rejecting a foreign browser origin at the host-daemon local API, or a rebound
Hostat the machine-auth proxy, is correct whether or not the firewall is ever relaxed. The relaxation is the risky half. As one PR, reverting the bug fix also reverts the hardening — exactly backwards, since a revert would most likely be prompted by a security concern. It would also bisect more clearly, and each guard could be verified against its own service without the reviewer holding the firewall change in mind.The case against is that the guards would land with no observable behavior change and no evident motivation; the reason each is needed is that the relaxation removes the accidental protection. That is a commit-message problem, not a correctness one, and the coverage table above is the artifact that would carry over either way.
One honest caveat: the split is not clean along the existing commits. Commits 3 and 4 each mix relaxation-side fixes (reserved-port assembly, pending state) with service-side guards (proxy
Origin, proxyHost), so a split would need re-partitioning rather than a cherry-pick. If a reviewer wants it split, that is the cost.Testing
Real reproduction, before the fix. A harness drove the production
createDesktopBrowserViewManager(bundled from source with esbuild) inside a real Electron 41 process under Xvfb, against three loopback servers: a page server on127.0.0.1:3009that also serves a same-port WebSocket, a WebSocket backend on127.0.0.1:3210, and a stand-in bb service. The page opened all three sockets and reported each verdict back to its own origin.Control, same page in a plain Chromium window (identical
webPreferences, no bb firewall):That pins the cancel on bb's
onBeforeRequesthandler, not on Chromium.After the fix, same harness, reserved ports supplied:
The reserved-port server logged no connection. Re-running the same binary with an empty reserved list let that socket through (
[bb-port-ws] connection accepted), which shows the reserved list is what holds it back.The unreservable proxy port. The same page fired blind
no-corsprobes at an unreserved loopback port, standing in for the machine-auth proxy's random port:Both reach the port under the relaxed firewall, and both are caught by the daemon-side guard. Real Chromium marks the
no-corsGET withSec-Fetch-Siteeven though it sends noOrigin.DNS rebinding. With
--host-resolver-rules="MAP rebind.example 127.0.0.1", the rebound request carries neither header, so the header check alone cannot see it:Re-run against the real proxy (bundled from
apps/host-daemon/src, fronting an upstream that logs the credential), no probe reaches upstream, while a Node client still does:Automated.
apps/desktop/test/desktop-browser-policy.test.ts: cross-origin loopback requests now pass; reserved ports are blocked under any loopback name, scheme, and with a default port; a page served from a reserved port still loads its own subresources;loopbackServicePortunit tests; andresolveReservedLoopbackPortstests covering the startup window (a null, not-yet-fetched daemon port must still reserve the packaged port), the dev instance, and a remote-server attachment.apps/desktop/test/desktop-browser-view-manager.test.ts: a manager-level regression test through the realonBeforeRequestwiring, covering the cross-port WebSocket, the reserved ports, and a public page that still reaches no loopback port.apps/host-daemon/src/machine-auth-proxy.test.ts: browser-originated HTTP requests and WebSocket handshakes are rejected without reaching upstream, and a Nodefetchcaller still gets through.apps/host-daemon/src/machine-auth-proxy.test.ts: browser-originated HTTP requests, browser WebSocket handshakes, and a rebound publicHostare all rejected without reaching upstream, while a Nodefetchcaller and the three real loopback authorities still get through.pnpm exec turbo run typecheck --filter=@bb/desktop --filter=@bb/host-daemonpasses.apps/host-daemon/src/local-api.test.ts: a foreign and a DNS-rebound browser origin are rejected before/open-in-targetruns, while the bb app's own origin and a caller sending noOriginstill succeed. Verified the test fails without the guard (expected 200 to be 403), so it protects the bug rather than passing by construction.pnpm exec turbo run test --filter=@bb/desktop --filter=@bb/host-daemon --forcepasses: 245 desktop tests, 549 host-daemon tests.Fixes #1452