Repository navigation
Conversation
A dev server bound to 127.0.0.1 on a remote host cannot be reached from the client at any address, so no URL rewrite helps it; only a forward does. This adds the host half. network.portForward reuses the browser tunnel's stream framing verbatim — it is already a general-purpose TCP multiplexer, so a forward is one stream per inbound connection and needs no new opcode or codec change. What it does not reuse is that method's authorization: the browser tunnel accepts any destination because a browser-host lease scopes it, which would be far too broad here. This method instead makes the destination itself the boundary and admits loopback only. The destination check is a strict allowlist rather than the existing classifyRemotePairingHostname, whose string-prefix test for '127.' would also admit 127.evil.example.com. Gated behind network.portForward.v1, so a host that predates it never advertises the method and clients keep today's behaviour.
… host Client half, part one: a 127.0.0.1-bound listener that opens one tunnel stream per inbound connection and pipes it to the remote port. It prefers the host's own port number and reports exact:false when it cannot get it, because a remapped port breaks everything that carries the original number — hot-reload sockets, OAuth redirect URIs, absolute asset paths. Callers must surface that rather than silently hand over a different URL. Bound to loopback only: the forward exists to make a remote port reachable on this machine, never to republish it to the network.
Client half, part two. PortForwardTransport carries one network.portForward subscription and the tunnel client riding it. It is separate from the browser tunnel's transport because that one is scoped by a browser-host lease and carries execution-host routing; a forward needs neither. PortForwardManager owns one subscription per environment and one listener per remote port. A forward is shared rather than per-consumer: two surfaces asking for the same remote port get the same local port, because handing out two would double the listeners and give the user two URLs for one dev server. Concurrent requests for the same port collapse through an in-flight map, without which each would bind its own listener and the loser would leak.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughAdds loopback port forwarding across the runtime and paired client. Shared schemas and validation restrict destinations to loopback hosts and valid ports. The runtime exposes Priority: ➖ Normal 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
src/main/port-forward/port-forward-transport.ts (1)
178-185: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winGuard
failagainst re-entry after an intentionalclose.
PortForwardTransport.close()setsclosedand callsBrowserNetworkTunnelClient.close()before clearingtunnelValue. The tunnel client invokesonClosedsynchronously, sofail()re-enters whiletunnelValueis non-null and emitsonLostfor an intentional shutdown.♻️ Proposed guard
private fail(error: Error, rejectReady: (error: Error) => void): void { + if (this.closed) { + return + } const wasReady = this.tunnelValue !== null this.close() rejectReady(error) if (wasReady) { this.options.onLost?.(error)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 0a27a284-287e-48f9-a142-dd9195b097c7
⛔ Files ignored due to path filters (1)
src/shared/rpc-contract/rpc-params-catalog.generated.tsis excluded by!**/*.generated.*
📒 Files selected for processing (12)
src/main/port-forward/port-forward-listener.test.tssrc/main/port-forward/port-forward-listener.tssrc/main/port-forward/port-forward-manager.test.tssrc/main/port-forward/port-forward-manager.tssrc/main/port-forward/port-forward-transport.tssrc/main/runtime/rpc/methods/index.tssrc/main/runtime/rpc/methods/port-forward.test.tssrc/main/runtime/rpc/methods/port-forward.tssrc/shared/loopback-forward-destination.test.tssrc/shared/loopback-forward-destination.tssrc/shared/port-forward-protocol.tssrc/shared/protocol-version.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
There was a problem hiding this comment.
Important
The security boundary and host advertisement both have gaps that need a look before merge: the host never advertises network.portForward.v1, and the loopback predicate classifies some strings as numeric loopback that the OS instead resolves as hostnames. Two lifecycle defects in the client transport/manager round it out.
Reviewed changes — read the complete 13-file diff at f0c2f222ee for review:
- Host RPC
network.portForward— streaming handler admits authenticated paired binary clients that negotiated the capability, then runsBrowserNetworkTunnelSessionwith a loopback-only connector; rejection surfaces asdestination_connect_failedwithout echoing the target. - Destination boundary — new
isLoopbackForwardDestination/isForwardablePortshared predicate, purpose-built rather than reusingclassifyRemotePairingHostname. - Client listener —
PortForwardListenerbinds127.0.0.1, prefers the host's own port, falls back withexact: false, and opens one tunnel stream per inbound connection. - Client transport + manager —
PortForwardTransportowns one subscription and the tunnel client;PortForwardManagershares one forward per remote port (in-flight collapse) and tears down on tunnel loss. - Registration and wire — method added to
ALL_RPC_METHODSand the params catalog, new capability constant, no opcode or codec change. - Tests — new suites for the listener (real sockets), manager sharing/concurrency/teardown, RPC admission, and the destination predicate.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…literal, and settle teardown once Advertise network.portForward.v1 in RUNTIME_CAPABILITIES so getStatus reports it; registration alone left every host looking like one that predates the feature. Dial the literal the loopback check validated instead of the caller's string. Normalised forms and leading-zero octets (127.0.0.08) were handed to getaddrinfo, which resolves them as hostnames and can answer off-host. Guard PortForwardTransport.fail against the re-entry its own close() causes, so a lost tunnel reports once and a deliberate close reports not at all. Re-check environment identity in PortForwardManager.release before closing, as open() already does, so a release cannot tear down the environment that replaced the one it observed.
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b1e43bfc-d7ec-497c-8621-0c173ba1d3af
📒 Files selected for processing (9)
src/main/port-forward/port-forward-manager.test.tssrc/main/port-forward/port-forward-manager.tssrc/main/port-forward/port-forward-transport.test.tssrc/main/port-forward/port-forward-transport.tssrc/main/runtime/rpc/methods/port-forward.test.tssrc/main/runtime/rpc/methods/port-forward.tssrc/shared/loopback-forward-destination.test.tssrc/shared/loopback-forward-destination.tssrc/shared/protocol-version.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/port-forward/port-forward-manager.test.ts
- src/shared/protocol-version.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — incremental review of 0a501c3bcd, the commit that settles the four findings from the prior pullfrog review; the full 14-file diff was re-read for context, and the five port-forward suites pass locally (40/40).
- Advertised the capability.
PORT_FORWARD_RUNTIME_CAPABILITYis now a member ofRUNTIME_CAPABILITIES, sogetStatus().capabilitiesreportsnetwork.portForward.v1.port-forward.test.tsasserts membership beside the registration assertion, matching the sibling-capability pattern. - Removed the validated-vs-dialled gap.
isLoopbackForwardDestinationbecameresolveLoopbackForwardHost, which returns the IP literal to dial (or null), andconnectLoopbackForwardDestinationconnects that literal instead oftarget.host. Leading-zero octets are refused outright rather than read as decimal;localhostis pinned to127.0.0.1;[::1]and trailing-dot forms normalise to a literal the resolver never sees. - Settled transport teardown once.
PortForwardTransport.failnow opens withif (this.closed) return, so the synchronousonClosedre-entry fromclose()no longer double-firesonLostor reports a deliberate close as a loss. Newport-forward-transport.test.tscovers both directions. - Closed the manager release race.
PortForwardManager.releasere-checksthis.environments.get(environmentId) === environmentbeforecloseEnvironment, mirroringopen; the regression test holdslistener.close()open and swaps the environment under the same id. - Test harness.
port-forward-manager.test.tsgained anopenerscapture and aholdClosegate, and the stream-opener assertion now proves the tunnel dials the remote port rather than the local one.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
…first The re-entry guard added in the previous commit short-circuits fail(), so a close() between acquiring the subscription and the ready event left nothing to settle the attach: start() — and the ensure() awaiting it — stayed pending for the life of the process. close() now rejects a waiting attach itself, and fail() rejects before tearing down so a real failure still surfaces its own error rather than the generic teardown one.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes — incremental review of 1c56ed47f4, the commit that settles a pending attach when the transport is closed before readiness. The full 14-file diff was re-read for context, and the new test was confirmed to fail when the fix is removed.
- Settled a pre-readiness close.
PortForwardTransport.close()now rejects the pendingreadypromise (port-forward-transport.ts:208), sostart()resolves its rejection instead of hanging for the process lifetime when close lands before thereadyframe. - Preserved the real failure reason.
fail()rejects the attach before callingclose()(:194-195), so the caller sees the actual error rather than the genericport_forward_transport_closedthatclose()would otherwise settle it with. - Added real coverage. The new test (
port-forward-transport.test.ts:93-107) times out without the fix; the harness gainedstubSubscription/settleSubscriptionso the test can hold a subscription without announcing readiness.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Tested live against a headless
|
| Same host | Desktop → host over a real link | |
|---|---|---|
Host advertises network.portForward.v1; a client without it is refused |
✅ | ✅ |
Loopback-only dev server reachable via ensure() |
✅ (exact: false: port taken on the same box) |
✅ exact: true, http://127.0.0.1:5199 |
| 8 MiB down + 8 MiB up, sha256 | ✅ | ✅ |
| WebSocket (HMR-style), 101 frames | ✅ | ✅ |
| 16 off-host / disguised destinations refused; canary listeners on every non-loopback address | ✅ 0 hits | ✅ 0 hits |
release() closes the local port |
✅ | ✅ |
| Real Vite app page load (139 requests, 25.9 MiB), median of 5 | – | 2.85 s / 3.15 s vs ssh -L 3.79 s / 3.82 s (two sessions) |
Worth fixing before the consumer lands:
- A forward goes dead silently after 65,536 connections. Stream ids are never reused, and ids are capped at 65,536 per tunnel (
browser-network-tunnel-client.ts:88). The browser route replaces an exhausted tunnel (paired-runtime-browser-network-route.ts:212), but the forward path has no equivalent. Reproduced live: exactly 65,536 connections succeeded (91 min at ~12/s, under the host's rate budget). Connection fix: route terminal paste through electron clipboard #65,537 and all 50 after it failed (socket hang up), whileonLostnever fired andmanager.get()still returned the forward. It looks healthy and is dead. A once-a-second health check reaches this in about 18 h. - Refusals are silent.
PortForwardListenerdrops the reason the tunnel already provides (port-forward-listener.ts:96,.catch(() => socket.destroy())). The inherited limits suit a browser but not general forwards. They are 32 streams shared by every forward to a host, 16 pending opens, and 128 opens per 10 s. Clients that open one connection per request just seeECONNRESET. Over a real link, bursts also hit the pending limit:pending_open_limit_exceededappeared in 1 of 3 raw 40-open probes, and 40 HTTP connections got only 17 through. - Choose the window before v1 ships. Throughput per forwarded connection is capped at window ÷ RTT, and I measured it (details below). At 256 KiB that's about 9 MiB/s at 28 ms and about 2.5 MiB/s at 100 ms. Meanwhile
ssh -Lreached 11.5 MiB/s on the same link. Becausenetwork.portForward.v1hasn't shipped, forward tunnels could still get a larger or adaptive window with no compatibility cost. After release, the same change needs a new capability. (Don't shrink it: a 64 KiB client made the page load 2.6× slower.)
Destination boundary: full matrix
Every one of these was refused with the generic destination_connect_failed, and the target was never echoed back:
- Metadata and off-host addresses:
169.254.169.254,0.0.0.0, docker172.17.0.1, a WireGuard10.x, the host's public v4 and v6,::ffff:172.17.0.1 - Names:
127.evil.example.com,localhost.evil.example.com,app.localhost,example.com - Alternative number forms:
0177.0.0.1,127.0.0.08,127.000.000.001,2130706433,0x7f000001
Ports 0 and 65536 are rejected client-side. localhost, ::1, [::1], [127.0.0.1] and ::ffff:127.0.0.1 connect; the bracket-stripping dials the literal. 127.1 is refused (fails closed). A refused open doesn't harm the tunnel.
The dev server listened on loopback only, and the same port on every non-loopback address was a canary listener: 0 connections during the probes on both legs. Scope note, consistent with "no reach beyond a terminal": any loopback listener is reachable, e.g. 127.0.0.1:22 connected.
Limits: measurements and a suggested fix
| Limit | Where | Measured |
|---|---|---|
| 32 concurrent streams | client, browser-network-tunnel-client.ts:85; one tunnel per host |
Locally 40 → 32 opened + 8 stream limit exceeded. With 10 connections held on a forward to :22, a forward to :5199 got exactly 22. |
| 16 pending opens | host, browser-network-tunnel-resource-budget.ts |
Desktop, raw 40-open bursts: 32/32/25 opened; run 3 had 7 × pending_open_limit_exceeded. Through HTTP, 40 → 17 and 32 → 30. Never seen locally. |
| 128 opens / 10 s | host, same file; per tunnel session | After 116 opens in ~6 s, a burst of 32 got exactly 12. It recovers as the window slides. Refused attempts don't count against it. |
Suggested, all client-only, so they work against every host version:
- Log the refusal reason at listener L96.
- Queue instead of resetting: at most 16 opens in flight, pace opens under 128 per 10 s, and hold accepted sockets briefly (with a deadline) while the tunnel is full. That turns the WAN bursts above into short waits.
- Replace a tunnel whose stream ids are exhausted, as the browser route does.
- Optionally, for updated hosts only: let
network.portForwardpass its own pending and rate budget to its session.
I'd avoid one tunnel per port: it multiplies the host's per-session budgets and does nothing for one busy port.
Benchmark: method and the window experiment
The host ran a real React + Tailwind Vite app in dev mode, bound to 127.0.0.1. From the desktop, a browser-like loader fetched index.html and then followed the static module graph over 6 keep-alive connections: 139 requests, 25.9 MiB, including a 17.7 MiB dependency chunk. Both paths ran over the same SSH link, alternating round by round, so the difference isolates this transport. Two sessions: 2,850 vs 3,788 ms and 3,149 vs 3,817 ms (forward vs ssh -L, medians of 5). Zero errors throughout. In Firefox through the forward: 163 requests, 31.6 MB, load 5.40 s.
Window experiment. Credit is explicit (every stream starts at sendCredit: 0), and peers reject only credit above 256 KiB (destination-flow.ts:85, client-stream-frames.ts:77). So a client granting less is wire-safe. I confirmed it live: a 64 KiB client against the unmodified host was byte-exact, with no credit errors, and the existing 77 tunnel unit tests pass with the default. But the 17.7 MiB file then moved at a flat 2.2–2.3 MiB/s in every round (64 KiB ÷ ~28 ms), while the SSH control in the same phase swung between 3 and 10 MiB/s. The page load took 8.3 s, 2.6× slower. At 256 KiB, the largest file never exceeded 8.0 MiB/s, while ssh -L (2 MiB channel windows) reached 11.5 MiB/s.
The missing Branch B wiring, from a serve user's side
The call site already exists. openWorkspacePortInBrowser (src/renderer/src/lib/workspace-port-actions.ts) sends a local port to the system browser on Shift/⌘-click (L123). A remote (environment) port always goes to the in-app browser via browser.tabCreate (L141). The consumer is roughly one more branch there:
- When the target is an
environmenthost that advertisesnetwork.portForward.v1, call an IPC to main →PortForwardManager.ensure()→shell.openUrl(handle.url). Hosts that don't advertise it keep today's behaviour. - Show a notice when
exact: false, since a remapped port breaks HMR sockets, OAuth redirects and absolute asset URLs. - Release forwards when the environment disconnects, and show the loss (
onLost) in the Ports UI. - In serve mode the right-sidebar Ports item is hidden altogether (
sshOnly: true,use-right-sidebar-activity-items.ts:112). Only the status-bar popover works there, so the consumer may want to lift that gate for environments with the capability.
#21807 edits the same function for the 0.0.0.0 case, so doing the two together avoids a second pass.
Notes on the build
- For the host I reused CI's
node-pty. A local Arch build of it needsGLIBC_2.42, and the afterPack glibc gate rightly refused to package it. pnpm typecheckruns 4tscprocesses at once (run-typecheck-projects-in-parallel.mjsonly runs them one at a time on single-core hosts). On a 16 GB machine that invoked the OOM killer. It's unrelated to this PR, and I can file it separately.pnpm lint's 2 warnings are inmobile/src/onboarding/*.test.ts, which this PR doesn't touch.
Happy to share the harness, the loader and the window patch, or to rerun all of it against a new revision. Had this problem myself, so happy to help and we'll be waiting for the merge to happen
Testing and analysis were done with Claude Code (Claude Opus 5.5); I reviewed the results and ran the desktop leg myself.
|
Thank you for this. Your design for the host side, a sibling |
|
Closing since this landed in #47994, which builds on your loopback port-forward transport and credits you as co-author. Thanks for the groundwork! |


ELI5
Some dev servers only accept connections from the machine they run on. When that machine is a remote Orca server, there is no address your laptop can use — not a tunnel address, not a VPN address, none. The only fix is to carry the connection.
This adds the pipe that carries it. Nothing uses the pipe yet.
What Changed
A dev server bound to
0.0.0.0on a remote host can be reached by rewriting the URL, which is #21807. A dev server bound to127.0.0.1cannot be reached at any address, because the kernel refuses packets arriving on a non-loopback interface. That case needs a forward, and this is the machinery for it.Host —
network.portForward. A streaming RPC method that accepts tunnel frames and connects them to loopback ports.Client — three pieces.
PortForwardListenerbinds127.0.0.1on the client and opens one tunnel stream per inbound connection.PortForwardTransportowns one subscription and the tunnel client riding it.PortForwardManagerkeeps one subscription per environment and one listener per remote port.The stream framing is reused verbatim. The browser tunnel's wire format is already a general-purpose TCP multiplexer —
Open { host, port }plus flow control — so a forward is one stream per connection. No new opcode, no codec change, no change toBrowserNetworkTunnelSession, which already takes an injectableconnect. Perdocs/reference/remote-wire-compatibility.mda new opcode would have needed negotiation; none is introduced.Why
The authorization is deliberately not reused.
network.browserTunnelaccepts any destination, which is safe there because a browser-host lease scopes it. A forward has no such scope, so the destination itself becomes the boundary: loopback only, enforced at connect time, with the rejection reported asdestination_connect_failedso the target is never echoed back.The loopback check is purpose-built rather than borrowed.
classifyRemotePairingHostnamelooks like the obvious helper, but its loopback test isnormalized.startsWith('127.')— a string comparison that also admits127.evil.example.com. Fine for labelling a pairing endpoint, a hole for deciding which socket a paired client may reach. The new check is a strict allowlist overlocalhost,127.0.0.0/8,::1and IPv4-mapped forms, and refuses subdomains oflocalhostbecause RFC 6761 notwithstanding, resolver behaviour varies and a wrong answer here opens a hole rather than merely failing.The check returns the address to dial, rather than approving a string someone else dials. A boolean leaves a gap between what was validated and what the socket reaches:
getaddrinfotreats127.0.0.08and[127.0.0.1]as hostnames, so a wildcard resolver or a search domain could answer them off-host after the check said loopback.resolveLoopbackForwardHosthands back a numeric literal instead, and that literal is what gets connected —net.connectskips the resolver for a literal, so the resolver is not in the path at all. Leading-zero octets are refused outright rather than read as decimal, since a decimal reading would disagree with the octal one the OS performs.Why land this before its consumer. Hosts and clients update independently —
remote-wire-compatibility.mdopens by saying mixed versions are the normal state. If the host half lands first, hosts in the wild already advertisenetwork.portForward.v1by the time the client half ships, and the feature works for people who have not updated their server. If both halves land together, every user needs both sides updated before anything works. #14440 landed contracts-only for the same reason. Happy to hold this until the consumer is ready if maintainers would rather see them together.Same-port preference. The listener asks for the host's own port number first and reports
exact: falsewhen it cannot have it. A remapped port breaks anything carrying the original number — hot-reload sockets, OAuth redirect URIs, absolute asset paths — so callers must surface that rather than quietly hand over a different URL.A forward is shared, not per-consumer. Two surfaces asking for the same remote port get the same local port; handing out two would double the listeners and give the user two URLs for one dev server. Concurrent requests collapse through an in-flight map, without which each binds its own listener and the loser leaks.
Linked Issue
Refs #21806 — Branch B.
Visual Proof
N/A— no user-visible surface. Nothing constructs these classes yet; the method is registered but no shipped client calls it.Testing
pnpm lint— full suite, clean. Worth notingcheck:dead-classesscanssrc/rendereronly, so it does not flag these main-process classes; that is a gap in the gate, not evidence the code is wired up.pnpm tc— clean.pnpm test— 41 tests.Coverage worth calling out:
The destination boundary is tested against the cases that matter, not just the happy path:
127.evil.example.com,localhost.evil.example.com,app.localhost,169.254.169.254,0.0.0.0, the leading-zero forms (127.0.0.08,127.000.000.001,0177.0.0.1), and the full127.0.0.0/8range. A dial-site test proves the resolved literal is what reaches a real listener, not the string the caller sent.The transport's teardown asserts a lost tunnel is reported once, a deliberate close is not reported as a loss, and a close that lands before readiness still settles the attach rather than leaving it pending.
The listener is exercised against real sockets end to end — byte carriage, same-port preference, fallback reporting
exact: false, several concurrent connections, and an open failure dropping the connection rather than hanging it.The manager covers sharing, concurrent collapse, per-environment isolation, teardown when a tunnel is lost, and dropping the subscription once the last forward is released.
I manually tested these changes locally
Automated tests added/updated, or explained why not below
AI Disclosure
Claude Opus 5, used for investigation, implementation, and tests.
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
network.portForward.v1ingetStatus(), and one that predates it does not, so a newer client simply does not offer the feature against an older host. No opcode, no codec change, no change to existing methods.Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)