Skip to content

STA-4150: define client-hosted browser contracts - #14953

Closed
Jinwoo-H wants to merge 1 commit into
mainfrom
sta-4150-landing-contracts-placement
Closed

Jinwoo-H wants to merge 1 commit into
mainfrom
sta-4150-landing-contracts-placement

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​790 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​790
Prod 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1124 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1124

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

  • Optional fields preserve old callers and old clients.
  • Existing server/offscreen browser behavior is unchanged.
  • No new stream opcode is introduced.

Validation

  • Full Node/CLI/web typecheck
  • Full lint, audits, max-lines, localization, and 86 reliability gates
  • Focused shared contract suite: 3 tests passed

Draft only. Do not merge outside the complete stack.

@Jinwoo-H Jinwoo-H changed the title sta 4150 landing contracts placement STA-4150: define client-hosted browser contracts Aug 16, 2026
@Jinwoo-H
Jinwoo-H force-pushed the sta-4150-landing-contracts-placement branch 11 times, most recently from 136329a to 230f2df Compare August 17, 2026 06:32
@Jinwoo-H
Jinwoo-H force-pushed the sta-4150-landing-contracts-placement branch from 230f2df to 9477959 Compare August 17, 2026 09:55
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review August 19, 2026 01:07
@coderabbitai

coderabbitai Bot commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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 94779

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides a summary, compatibility notes, and validation details, but it omits most required template sections and the required linked issue. Complete the required sections, add a linked issue such as “Fixes #...”, provide visual proof or N/A, and include testing, review, checklist, and author details.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: defining contracts for client-hosted browsers.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (12)
src/shared/browser-network-tunnel-protocol.ts (1)

162-171: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename connectionFrame to match its meaning.

connectionFrame is true for stream-scoped frames and false for Ping/Pong, which are the connection-scoped frames. The name states the opposite of the value. Rename it to streamScopedFrame.

♻️ 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 win

Reuse the generation rule from the protocol module.

validateBrowserNetworkTunnelGeneration repeats the exact bounds and error text already implemented in validateFrameIdentity in src/shared/browser-network-tunnel-protocol.ts (lines 155-161), including the literal 0xffff_ffff. Two copies of the same identity rule can drift. Export the generation validator or the MAX_UINT32 bound from the protocol module and call it here.

src/shared/protocol-version.ts (1)

76-77: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Align the new capability identifiers with the existing browser namespace.

BROWSER_NETWORK_TUNNEL_RUNTIME_CAPABILITY uses the network. prefix, but every other browser capability in this file uses browser. (browser.screencast.v1 at line 70, browser.tab-create-known-id.v1 at 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_CAPABILITIES yet, so changing them now costs nothing. Consider browser.network-tunnel.v1 and browser.client-host.v1.

src/shared/browser-network-tunnel-protocol.test.ts (2)

46-76: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add coverage for the reserved-byte check.

decodeBrowserNetworkTunnelFrame rejects a frame when byte 3 is non-zero (src/shared/browser-network-tunnel-protocol.ts line 65). No test exercises that branch. Add a case that sets byte 3 and expects null.

💚 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 win

Add lower-bound cases for generation and stream id.

Both assertions cover only the upper bound. The lower bounds are untested. tunnelGeneration: 0 must throw. streamId: 0 must throw for a stream-scoped opcode such as Data, but must be accepted for Ping. That last rule is the connection-scoped exception in validateFrameIdentity, 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 win

Make readExact fail fast when the socket closes early.

The loop awaits only 'data'. events.once rejects 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 win

Add coverage for the IPv4, IPv6, and auth-rejection branches.

Every request test uses the domain address type. parseSocksRequest has three address branches, and the IPv4 and IPv6 branches are untested. The IPv6 branch calls formatIpv6, which produces the expanded form 0:0:0:0:0:0:0:1 rather 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 method 0x02.

💚 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 current formatIpv6 output, which is the behavior flagged in src/main/browser/remote-browser-socks-server.ts lines 279-284.

src/main/browser/browser-network-tunnel-session.ts (1)

236-244: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Consider a deadline for a destination close that waits on client credit.

onDestinationClose defers finalizeDestinationClose while pendingToClient is not empty. The remaining flush only runs when the client sends a WindowUpdate or when new destination data arrives. After the destination socket closes, no more data arrives. If the client never grants credit, the stream entry stays in this.streams and never sends Close.

The exposure is bounded by BROWSER_NETWORK_TUNNEL_MAX_STREAMS and 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 calling failStream(stream, 'destination_drain_timeout') on expiry.

src/main/browser/browser-network-tunnel-destination-flow.ts (1)

46-49: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Separate the malformed-payload case from the credit-overflow case.

decodeBrowserNetworkTunnelWindowUpdate returns null for a payload that is not exactly four bytes or that carries an out-of-range value. Line 47 maps that case to send_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 win

Derive the overflow chunk size from BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES.

The test hardcodes 64 * 1024 and a loop count of 4. That pair only exhausts the receive window while BROWSER_NETWORK_TUNNEL_INITIAL_WINDOW_BYTES equals 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 win

Close the session so the connect timer does not outlive the test.

openStream arms connectTimeout with BROWSER_NETWORK_TUNNEL_CONNECT_TIMEOUT_MS for every accepted Open. This test opens stream 3 at Line 294, never emits connect, and never calls session.close(). The timer stays pending after the test ends and can fire during a later test in the same worker. Add session.close() at the end, or enable vi.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_timeout has no coverage in this file. Consider adding a fake-timer test that advances past BROWSER_NETWORK_TUNNEL_CONNECT_TIMEOUT_MS and asserts the Error frame and socket destruction.


202-229: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the session-wide shutdown after a reused stream ID.

openStream calls this.close() after it reports stream_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

📥 Commits

Reviewing files that changed from the base of the PR and between 7ae6aed and 9477959.

📒 Files selected for processing (12)
  • config/reliability-gates.jsonc
  • src/main/browser/browser-network-tunnel-destination-flow.ts
  • src/main/browser/browser-network-tunnel-frame-sender.ts
  • src/main/browser/browser-network-tunnel-session.test.ts
  • src/main/browser/browser-network-tunnel-session.ts
  • src/main/browser/browser-network-tunnel-stream-state.ts
  • src/main/browser/remote-browser-socks-server.test.ts
  • src/main/browser/remote-browser-socks-server.ts
  • src/shared/browser-network-capabilities.test.ts
  • src/shared/browser-network-tunnel-protocol.test.ts
  • src/shared/browser-network-tunnel-protocol.ts
  • src/shared/protocol-version.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Comment on lines +52 to +71
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

Suggested change
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

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

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.

@Jinwoo-H Jinwoo-H closed this Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant