Repository navigation
Conversation
136329a to
230f2df
Compare
230f2df to
9477959
Compare
📝 WalkthroughWalkthroughAdds a browser network tunnel protocol with frame, payload, identity, and flow-control validation. Adds session and stream state management with bounded buffering, credit settlement, lifecycle handling, stale-stream rejection, and fail-closed transport errors. Adds a loopback-only SOCKS5 server with IPv4, domain, and IPv6 routing, bounded pipelining, and deterministic cleanup. Adds comprehensive protocol, session, SOCKS, capability, and reliability-gate coverage. Merge Risk: 🟠 High · up to The new browser tunnel server can crash the main application process if a post-startup socket or accept error occurs because its error handling is removed after startup; this is a high-impact availability risk, so the PR is not merge-ready until a persistent handler is retained. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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: 1
🧹 Nitpick comments (12)
src/shared/browser-network-tunnel-protocol.ts (1)
162-171: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRename
connectionFrameto match its meaning.
connectionFrameistruefor stream-scoped frames andfalsefor Ping/Pong, which are the connection-scoped frames. The name states the opposite of the value. Rename it tostreamScopedFrame.♻️ Proposed rename
- const connectionFrame = + const streamScopedFrame = frame.opcode !== BrowserNetworkTunnelOpcode.Ping && frame.opcode !== BrowserNetworkTunnelOpcode.Pong if ( !Number.isInteger(frame.streamId) || - frame.streamId < (connectionFrame ? 1 : 0) || + frame.streamId < (streamScopedFrame ? 1 : 0) || frame.streamId > MAX_UINT32 ) {src/main/browser/browser-network-tunnel-stream-state.ts (1)
7-11: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse the generation rule from the protocol module.
validateBrowserNetworkTunnelGenerationrepeats the exact bounds and error text already implemented invalidateFrameIdentityinsrc/shared/browser-network-tunnel-protocol.ts(lines 155-161), including the literal0xffff_ffff. Two copies of the same identity rule can drift. Export the generation validator or theMAX_UINT32bound from the protocol module and call it here.src/shared/protocol-version.ts (1)
76-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAlign the new capability identifiers with the existing browser namespace.
BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITYuses thenetwork.prefix, but every other browser capability in this file usesbrowser.(browser.screencast.v1at line 70,browser.tab-create-known-id.v1at lines 74-75). Both new identifiers also use camelCase segments, while most identifiers here use kebab-case segments.These strings are wire identifiers. After a release advertises them, renaming requires a version bump and dual support. Neither identifier is in
RUNTIME_CAPABILITIESyet, so changing them now costs nothing. Considerbrowser.network-tunnel.v1andbrowser.client-host.v1.src/shared/browser-network-tunnel-protocol.test.ts (2)
46-76: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd coverage for the reserved-byte check.
decodeBrowserNetworkTunnelFramerejects a frame when byte 3 is non-zero (src/shared/browser-network-tunnel-protocol.tsline 65). No test exercises that branch. Add a case that sets byte 3 and expectsnull.💚 Proposed added case
const badOpcode = encoded.slice() badOpcode[2] = 255 expect(decodeBrowserNetworkTunnelFrame(badOpcode)).toBeNull() + const badReserved = encoded.slice() + badReserved[3] = 1 + expect(decodeBrowserNetworkTunnelFrame(badReserved)).toBeNull() + const wrongLength = encoded.slice()
92-110: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd lower-bound cases for generation and stream id.
Both assertions cover only the upper bound. The lower bounds are untested.
tunnelGeneration: 0must throw.streamId: 0must throw for a stream-scoped opcode such asData, but must be accepted forPing. That last rule is the connection-scoped exception invalidateFrameIdentity, and no test asserts it.💚 Proposed added cases
).toThrow('stream id') + expect(() => + encodeBrowserNetworkTunnelFrame({ + opcode: BrowserNetworkTunnelOpcode.Ping, + tunnelGeneration: 0, + streamId: 0, + payload + }) + ).toThrow('generation') + expect(() => + encodeBrowserNetworkTunnelFrame({ + opcode: BrowserNetworkTunnelOpcode.Data, + tunnelGeneration: 1, + streamId: 0, + payload + }) + ).toThrow('stream id') + expect( + encodeBrowserNetworkTunnelFrame({ + opcode: BrowserNetworkTunnelOpcode.Ping, + tunnelGeneration: 1, + streamId: 0, + payload + }) + ).toBeInstanceOf(Uint8Array) })src/main/browser/remote-browser-socks-server.test.ts (2)
20-33: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake
readExactfail fast when the socket closes early.The loop awaits only
'data'.events.oncerejects on'error', but a clean'close'with no error leaves the promise pending forever. If a regression closes the connection instead of sending the expected reply, the test hangs until the Vitest timeout instead of failing with a clear message.Race the data wait against
'close'.💚 Proposed refactor
async function readExact(socket: Socket, size: number): Promise<Uint8Array> { const chunks: Buffer[] = [] let total = 0 while (total < size) { - const [chunk] = (await once(socket, 'data')) as [Buffer] + const [chunk] = (await Promise.race([ + once(socket, 'data'), + once(socket, 'close').then(() => { + throw new Error(`socket closed after ${total} of ${size} bytes`) + }) + ])) as [Buffer] chunks.push(chunk) total += chunk.byteLength }
51-196: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd coverage for the IPv4, IPv6, and auth-rejection branches.
Every request test uses the domain address type.
parseSocksRequesthas three address branches, and the IPv4 and IPv6 branches are untested. The IPv6 branch callsformatIpv6, which produces the expanded form0:0:0:0:0:0:0:1rather than::1. No current test would detect that. The greeting rejection path that writes[5, 0xff]when the client offers no NO_AUTH method is also untested.Add three cases: an IPv4 CONNECT request, an IPv6 CONNECT request that asserts the exact host string passed to
open, and a greeting that offers only method0x02.💚 Proposed added cases
+ it('routes IPv4 and IPv6 address types', async () => { + const open = vi.fn(async () => new PassThrough()) + const server = new RemoteBrowserSocksServer({ open }) + servers.push(server) + + const v4 = await connectClient(server) + await greet(v4) + const v4Request = new Uint8Array([5, 1, 0, 1, 127, 0, 0, 1, 0x1f, 0x90]) + v4.write(v4Request) + await readExact(v4, 10) + expect(open).toHaveBeenCalledWith({ host: '127.0.0.1', port: 8080 }) + v4.destroy() + + const v6 = await connectClient(server) + await greet(v6) + const v6Request = new Uint8Array([5, 1, 0, 4, ...new Uint8Array(15), 1, 0x1f, 0x90]) + v6.write(v6Request) + await readExact(v6, 10) + expect(open).toHaveBeenLastCalledWith({ host: '::1', port: 8080 }) + v6.destroy() + }) + + it('rejects a greeting without the no-auth method', async () => { + const open = vi.fn(async () => new PassThrough()) + const server = new RemoteBrowserSocksServer({ open }) + servers.push(server) + const socket = await connectClient(server) + + socket.write(new Uint8Array([5, 1, 2])) + + expect(Array.from(await readExact(socket, 2))).toEqual([5, 0xff]) + expect(open).not.toHaveBeenCalled() + })The IPv6 assertion expects the canonical
::1. It fails against the currentformatIpv6output, which is the behavior flagged insrc/main/browser/remote-browser-socks-server.tslines 279-284.src/main/browser/browser-network-tunnel-session.ts (1)
236-244: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winConsider a deadline for a destination close that waits on client credit.
onDestinationClosedefersfinalizeDestinationClosewhilependingToClientis not empty. The remaining flush only runs when the client sends aWindowUpdateor when new destination data arrives. After the destination socket closes, no more data arrives. If the client never grants credit, the stream entry stays inthis.streamsand never sendsClose.The exposure is bounded by
BROWSER_NETWORK_TUNNEL_MAX_STREAMSand by the pending-byte limits, so this is not a crash path. A peer can still park 128 streams indefinitely. Consider arming a drain timeout when the destination closes with pending bytes, then callingfailStream(stream, 'destination_drain_timeout')on expiry.src/main/browser/browser-network-tunnel-destination-flow.ts (1)
46-49: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winSeparate the malformed-payload case from the credit-overflow case.
decodeBrowserNetworkTunnelWindowUpdatereturnsnullfor a payload that is not exactly four bytes or that carries an out-of-range value. Line 47 maps that case tosend_window_overflow. The error code travels to the client on the wire, so a malformed frame reports a window overflow. Use a distinct code for the decode failure.♻️ Proposed change
const credit = decodeBrowserNetworkTunnelWindowUpdate(payload) - if (!credit || stream.sendCredit + credit > BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES) { + if (!credit) { + return 'invalid_window_update' + } + if (stream.sendCredit + credit > BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES) { return 'send_window_overflow' }src/main/browser/browser-network-tunnel-session.test.ts (3)
450-454: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive the overflow chunk size from
BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES.The test hardcodes
64 * 1024and a loop count of4. That pair only exhausts the receive window whileBROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTESequals 262144. If the constant grows, the final one-byte frame stays inside the window and the test passes without exercising the overflow path. The constant is already imported at Line 12.♻️ Proposed change
- const chunk = new Uint8Array(64 * 1024) - for (let index = 0; index < 4; index += 1) { + const chunk = new Uint8Array(64 * 1024) + const chunks = BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES / chunk.byteLength + expect(Number.isInteger(chunks)).toBe(true) + for (let index = 0; index < chunks; index += 1) { session.handleBinary(frame(BrowserNetworkTunnelOpcode.Data, chunk)) }
274-298: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winClose the session so the connect timer does not outlive the test.
openStreamarmsconnectTimeoutwithBROWSER_NETWORK_TUNNEL_CONNECT_TIMEOUT_MSfor every acceptedOpen. This test opens stream 3 at Line 294, never emitsconnect, and never callssession.close(). The timer stays pending after the test ends and can fire during a later test in the same worker. Addsession.close()at the end, or enablevi.useFakeTimers().The same pattern applies to the tests at Lines 168-200 and 202-229 for the streams that never connect; the disposal test does call
session.close(), so only the uncovered streams remain.Separately,
destination_connect_timeouthas no coverage in this file. Consider adding a fake-timer test that advances pastBROWSER_NETWORK_TUNNEL_CONNECT_TIMEOUT_MSand asserts theErrorframe and socket destruction.
202-229: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the session-wide shutdown after a reused stream ID.
openStreamcallsthis.close()after it reportsstream_id_reused. The test verifies the error frame and the destroyed first socket, but it does not verify that the session stopped processing later frames. Add an assertion that a subsequent valid frame produces no new output.♻️ Proposed addition
expect(error ? new TextDecoder().decode(error.payload) : '').toBe('stream_id_reused') + + const sentCount = sent.length + session.handleBinary(frame(BrowserNetworkTunnelOpcode.Ping)) + expect(sent).toHaveLength(sentCount)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 1d99433a-6406-49d1-9484-abff42ec6a5d
📒 Files selected for processing (12)
config/reliability-gates.jsoncsrc/main/browser/browser-network-tunnel-destination-flow.tssrc/main/browser/browser-network-tunnel-frame-sender.tssrc/main/browser/browser-network-tunnel-session.test.tssrc/main/browser/browser-network-tunnel-session.tssrc/main/browser/browser-network-tunnel-stream-state.tssrc/main/browser/remote-browser-socks-server.test.tssrc/main/browser/remote-browser-socks-server.tssrc/shared/browser-network-capabilities.test.tssrc/shared/browser-network-tunnel-protocol.test.tssrc/shared/browser-network-tunnel-protocol.tssrc/shared/protocol-version.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| this.listenPromise = new Promise((resolve, reject) => { | ||
| const onError = (error: Error): void => { | ||
| this.state = 'closed' | ||
| reject(error) | ||
| } | ||
| this.server.once('error', onError) | ||
| this.server.listen(0, '127.0.0.1', () => { | ||
| this.server.off('error', onError) | ||
| const address = this.server.address() | ||
| if (!address || typeof address === 'string') { | ||
| reject(new Error('Browser SOCKS server did not bind a TCP address')) | ||
| return | ||
| } | ||
| if (this.state === 'starting') { | ||
| this.state = 'listening' | ||
| } | ||
| resolve({ host: '127.0.0.1', port: address.port }) | ||
| }) | ||
| }) | ||
| return this.listenPromise |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Attach a persistent error handler to the server.
onError is removed at line 59 after a successful bind. After that, the net.Server has no error listener. A net.Server emits error for post-bind failures such as EMFILE or ENFILE on accept. An error event with no listener throws and crashes the Electron main process.
Keep a permanent handler that is separate from the one-shot bind rejection.
🛡️ Proposed fix
this.state = 'starting'
this.listenPromise = new Promise((resolve, reject) => {
const onError = (error: Error): void => {
this.state = 'closed'
reject(error)
}
this.server.once('error', onError)
this.server.listen(0, '127.0.0.1', () => {
this.server.off('error', onError)
+ // Keep the server from throwing on post-bind accept errors.
+ this.server.on('error', () => undefined)
const address = this.server.address()📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| this.listenPromise = new Promise((resolve, reject) => { | |
| const onError = (error: Error): void => { | |
| this.state = 'closed' | |
| reject(error) | |
| } | |
| this.server.once('error', onError) | |
| this.server.listen(0, '127.0.0.1', () => { | |
| this.server.off('error', onError) | |
| const address = this.server.address() | |
| if (!address || typeof address === 'string') { | |
| reject(new Error('Browser SOCKS server did not bind a TCP address')) | |
| return | |
| } | |
| if (this.state === 'starting') { | |
| this.state = 'listening' | |
| } | |
| resolve({ host: '127.0.0.1', port: address.port }) | |
| }) | |
| }) | |
| return this.listenPromise | |
| this.listenPromise = new Promise((resolve, reject) => { | |
| const onError = (error: Error): void => { | |
| this.state = 'closed' | |
| reject(error) | |
| } | |
| this.server.once('error', onError) | |
| this.server.listen(0, '127.0.0.1', () => { | |
| this.server.off('error', onError) | |
| // Keep the server from throwing on post-bind accept errors. | |
| this.server.on('error', () => undefined) | |
| const address = this.server.address() | |
| if (!address || typeof address === 'string') { | |
| reject(new Error('Browser SOCKS server did not bind a TCP address')) | |
| return | |
| } | |
| if (this.state === 'starting') { | |
| this.state = 'listening' | |
| } | |
| resolve({ host: '127.0.0.1', port: address.port }) | |
| }) | |
| }) | |
| return this.listenPromise |
|
Superseded by the consolidated PR #15448 (the full STA-4150 feature merged with latest main). This PR's diff remains as the per-layer review view; its CI was fully green at close. |
Summary
Stack 1/5 for STA-4150. Defines the additive, capability-gated client-host, tunnel, lease, placement, and command contracts. This layer does not advertise support or change normal browser placement.
Compatibility
Validation
Draft only. Do not merge outside the complete stack.