Skip to content

Commit c03eafd

Browse files
authored
refactor(proxy): share opaque transport with desktop relay (#7120)
Contributed by @lcxhh521. Remote exact-head validation (hosted GitHub Actions stalled; local tests not run by maintainer rule): union candidate codex/prr-integ-6 (368006f, tree 27fdc37) on mini (Windows) and lidge (Linux), typecheck + full suite, compared with base-dev 4ae4936 on each host. Co-authored-by: lcxhh <lcxhh521@gmail.com>
1 parent 9e0ed51 commit c03eafd

12 files changed

Lines changed: 976 additions & 64 deletions

‎docs-site/src/content/docs/guides/codex-integration.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1621,3 +1621,14 @@ The shared SSE decoder accepts LF, CRLF and standalone CR line endings, even whe
16211621
Choosing an account-qualified model does not enable credit spending. Stored accounts obey **Use credits after limit** during authentication, when credentials are prepared, and before Responses HTTP or WebSocket dispatch after pacing or retry waits. A held request reports the credit policy, not an authentication failure; wait for the reset, choose another account, or explicitly enable that account’s credit spending.
16221622

16231623
Stored-account vision and web-search helpers also recheck this policy before sending, including retries. If consent changes or a limit is reached after helper selection, the helper reports the policy refusal without sending that attempt. The standalone search relay returns a reset-bound 429. Caller-owned Direct credentials retain their existing behavior.
1624+
1625+
## Native Desktop relay CONNECT validation
1626+
1627+
The Desktop relay's existing HTTP/HTTPS CONNECT transport now rejects malformed
1628+
proxy response headers and ambiguous HTTP Basic usernames containing colons.
1629+
Decoded credential pairs are limited to 4096 UTF-8 bytes. If your selected proxy
1630+
is rejected, correct its configuration or response; the relay does not silently
1631+
switch to a direct connection.
1632+
1633+
Proxy selection, SOCKS5/SOCKS5h support, certificate verification, and connection
1634+
lifecycle are unchanged. Both SOCKS spellings retain remote target DNS resolution.

‎scripts/test-layout/layout.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -855,6 +855,8 @@
855855
"deepseek-responses-item-id-repair.test.ts": "providers",
856856
"management-desktop-compatibility-routes.test.ts": "server", "management-desktop-compatibility-runtime-routes.test.ts": "server", "server-desktop-compatibility-startup.test.ts": "server", "management-desktop-compatibility-settings.test.ts": "server",
857857
"optional-desktop-upstream.test.ts": "lib",
858+
"opaque-proxy-tunnel.test.ts": "lib",
859+
"opaque-proxy-tunnel-protocol.test.ts": "lib",
858860
"destination-policy-resolved.test.ts": "routing",
859861
"devin-adapter-reset-wait.test.ts": "providers",
860862
"devin-adapter.test.ts": "providers",

‎src/lib/desktop-upstream-tunnel.ts‎

Lines changed: 18 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
import { connect as tcpConnect, isIP, type Socket } from "node:net";
2-
import { checkServerIdentity, connect as tlsConnect, type TLSSocket } from "node:tls";
1+
import { connect as tcpConnect, type Socket } from "node:net";
2+
import { connect as tlsConnect, type TLSSocket } from "node:tls";
33
import { desktopProxyFor } from "./desktop-proxy-route";
4-
import { socks5Credentials, socks5Handshake } from "./socks5-handshake";
4+
import { dialTunnel, type OpaqueProxyRoute } from "./opaque-proxy-tunnel";
55

6-
// Shares the SOCKS exchange extracted by lcxhh521 in PR #5947 (efdccdbfac3f).
7-
// Lifecycle here additionally bounds the entire dial and handles close/abort/header limits.
6+
// The shared opaque dialer owns proxy framing; this caller owns fixed-target
7+
// TLS and bounds the entire connection, including the target TLS handshake.
88
export interface DesktopTunnelOptions {
99
proxy?: string | false;
1010
signal?: AbortSignal;
@@ -15,37 +15,6 @@ export interface DesktopTunnelOptions {
1515
proxyCa?: string;
1616
}
1717
const fail = () => new Error("desktop_upstream_connection_failed");
18-
class HandshakeReader {
19-
private buffer: Buffer<ArrayBufferLike> = Buffer.alloc(0);
20-
private failure: Error | null = null;
21-
private waiting: { ready: () => boolean; resolve: () => void; reject: (error: Error) => void } | null = null;
22-
private onData = (chunk: Buffer) => {
23-
if (this.buffer.length + chunk.length > 65536) { this.onFailure(); return; }
24-
this.buffer = Buffer.concat([this.buffer, chunk]);
25-
if (this.waiting?.ready()) { const current = this.waiting; this.waiting = null; current.resolve(); }
26-
};
27-
private onFailure = () => { this.failure = fail(); const current = this.waiting; this.waiting = null; current?.reject(this.failure); };
28-
constructor(private socket: Socket, private signal: AbortSignal) {
29-
socket.on("data", this.onData); socket.once("error", this.onFailure); socket.once("end", this.onFailure); socket.once("close", this.onFailure);
30-
signal.addEventListener("abort", this.onFailure, { once: true }); if (signal.aborted) this.onFailure(); socket.resume();
31-
}
32-
write(bytes: Uint8Array | string): void { if (this.failure) throw this.failure; this.socket.write(bytes); }
33-
private async until(ready: () => boolean): Promise<void> {
34-
if (this.failure) throw this.failure;
35-
if (ready()) return;
36-
if (this.waiting) throw fail();
37-
await new Promise<void>((resolve, reject) => { this.waiting = { ready, resolve, reject }; });
38-
}
39-
private take(length: number): Buffer { const out = this.buffer.subarray(0, length); this.buffer = this.buffer.subarray(length); return out; }
40-
async readExact(length: number): Promise<Buffer> { await this.until(() => this.buffer.length >= length); return this.take(length); }
41-
async readHead(): Promise<string> { await this.until(() => this.buffer.indexOf("\r\n\r\n") >= 0); return this.take(this.buffer.indexOf("\r\n\r\n") + 4).toString("latin1"); }
42-
dispose(): void {
43-
this.socket.pause(); this.socket.removeListener("data", this.onData); this.socket.removeListener("error", this.onFailure);
44-
this.socket.removeListener("end", this.onFailure); this.socket.removeListener("close", this.onFailure);
45-
this.signal.removeEventListener("abort", this.onFailure);
46-
if (this.buffer.length) this.socket.unshift(this.buffer); this.buffer = Buffer.alloc(0); this.onFailure();
47-
}
48-
}
4918
function waitConnected(socket: Socket, event: "connect" | "secureConnect", signal: AbortSignal): Promise<void> {
5019
return new Promise((resolve, reject) => {
5120
const dispose = () => { socket.off(event, done); socket.off("error", failure); socket.off("close", failure); signal.removeEventListener("abort", failure); };
@@ -76,25 +45,21 @@ export async function dialDesktopUpstream(options: DesktopTunnelOptions = {}): P
7645
const url = new URL(proxy), protocol = url.protocol;
7746
if (!["http:", "https:", "socks5:", "socks5h:"].includes(protocol) || !url.hostname || url.search || url.hash || url.pathname !== "" && url.pathname !== "/") throw fail();
7847
const host = url.hostname.replace(/^\[|\]$/g, ""), port = Number(url.port) || (protocol === "https:" ? 443 : protocol.startsWith("socks") ? 1080 : 80);
79-
raw = own(tcpConnect({ host, port })); await waitConnected(raw, "connect", signal);
80-
if (protocol === "https:") {
81-
raw = own(tlsConnect({ socket: raw, servername: isIP(host) ? undefined : host, ca: options.proxyCa,
82-
rejectUnauthorized: true, checkServerIdentity: (_name, certificate) => checkServerIdentity(host, certificate), ALPNProtocols: ["http/1.1"] }));
83-
await waitConnected(raw, "secureConnect", signal);
84-
}
85-
const reader = new HandshakeReader(raw, signal);
86-
try {
87-
if (protocol.startsWith("socks")) await socks5Handshake(reader, target, socks5Credentials(url));
88-
else {
89-
const authority = `${target.host}:${target.port}`;
90-
const lines = [`CONNECT ${authority} HTTP/1.1`, `Host: ${authority}`];
91-
if (url.username || url.password) lines.push(`Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`).toString("base64")}`);
92-
reader.write(lines.join("\r\n") + "\r\n\r\n");
93-
if (!/^HTTP\/1\.[01] 2\d\d(?: |\r)/.test(await reader.readHead())) throw fail();
94-
}
95-
} finally { reader.dispose(); }
48+
const credentials = url.username || url.password
49+
? { username: decodeURIComponent(url.username), password: decodeURIComponent(url.password) }
50+
: {};
51+
const endpoint = { host, port, ...credentials };
52+
const route: OpaqueProxyRoute = protocol === "https:"
53+
? { ...endpoint, kind: "https", proxyCa: options.proxyCa }
54+
: { ...endpoint, kind: protocol.slice(0, -1) as "http" | "socks5" | "socks5h" };
55+
const authority = `${target.host.includes(":") ? `[${target.host}]` : target.host}:${target.port}`;
56+
// The route resolver remains authoritative; a failed proxy never becomes DIRECT.
57+
raw = own(await dialTunnel(authority, route, { signal, timeoutMs: timeout, maxHeaderBytes: 65536 }));
9658
}
9759
if (signal.aborted || raw.destroyed) throw fail();
60+
// This consumer historically closes its writable side after peer EOF. The
61+
// shared opaque transport preserves half-closes for callers that need them.
62+
raw.allowHalfOpen = false;
9863
const secured = own(tlsConnect({ socket: raw, servername: "chatgpt.com", ca: options.ca, rejectUnauthorized: true, ALPNProtocols: ["http/1.1"] }));
9964
// The CONNECT reader paused its stream before handing buffered bytes back. Bun's
10065
// TLS-over-TLS path needs the outer TLS stream explicitly resumed for the new handshake.

0 commit comments

Comments
 (0)