Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 28 additions & 1 deletion bin/codex-proxy.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,8 @@ const wsEncodeFrame = (payload, opcode = 0x1) => {
return Buffer.concat([header, mask, masked]);
};

const MAX_APP_SERVER_FRAME_BYTES = 1024 * 1024;

class AppServerClient {
constructor(socketPath) {
this.socketPath = socketPath;
Expand All @@ -523,6 +525,7 @@ class AppServerClient {
this.loadedThreads = new Set();
this.buffer = Buffer.alloc(0);
this.fragments = [];
this.fragmentBytes = 0;
this.handshaked = false;
}

Expand Down Expand Up @@ -592,9 +595,18 @@ class AppServerClient {
this.pending.clear();
for (const st of this.turnStates.values()) st.fail(err);
this.turnStates.clear();
this.buffer = Buffer.alloc(0);
this.fragments = [];
this.fragmentBytes = 0;
if (appServerClient === this) appServerClient = null;
}

rejectFrameLength(length, kind = 'frame') {
const err = new Error(`app-server ${kind} length ${length} exceeds ${MAX_APP_SERVER_FRAME_BYTES}-byte limit`);
this.handleClose(err);
try { this.sock && this.sock.destroy(); } catch {}
Comment on lines +606 to +607

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Settle initialization safely before rejecting a buffered frame

If an initialize RPC response and an oversized frame header arrive in the same socket data event, parsing the response queues the initialization success callback, but this call marks the client dead before that callback runs. The callback in connect() then calls this.send({ method: 'initialized' }), which throws app-server not connected; its returned promise has no rejection handler, so Node's default unhandled-rejection behavior terminates the proxy instead of falling back to exec. Reproducing the same input against the parent commit initializes successfully, whereas this commit produces the unhandled rejection. Ensure frame rejection also safely settles initialization and prevents the queued success callback from sending on a dead client.

Useful? React with 👍 / 👎.

}

send(obj) {
if (!this.sock || this.dead) throw new Error('app-server not connected');
this.sock.write(wsEncodeFrame(JSON.stringify(obj)));
Expand All @@ -614,7 +626,20 @@ class AppServerClient {
len = this.buffer.readUInt16BE(off); off += 2;
} else if (len === 127) {
if (this.buffer.length < off + 8) return;
len = Number(this.buffer.readBigUInt64BE(off)); off += 8;
const claimed = this.buffer.readBigUInt64BE(off); off += 8;
if (claimed > BigInt(Number.MAX_SAFE_INTEGER)) {
this.rejectFrameLength(claimed);
return;
}
len = Number(claimed);
}
if (len > MAX_APP_SERVER_FRAME_BYTES) {
this.rejectFrameLength(len);
return;
}
if (this.fragmentBytes + len > MAX_APP_SERVER_FRAME_BYTES) {
this.rejectFrameLength(this.fragmentBytes + len, 'message');
return;
Comment on lines +640 to +642

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exclude control frames from the aggregate message-size check

When a ping arrives between fragments of a message near the cap, this check adds the ping payload to the accumulated message size before the ping handler can run. For example, a 1,048,575-byte first fragment, an interleaved 2-byte ping, and a 1-byte continuation form a valid message exactly at the limit, but the connection is destroyed on the ping with a claimed message length of 1,048,577. This unnecessarily fails active turns and triggers exec fallback, or a streaming error if output was already emitted. Apply the aggregate check only to data/continuation frames, excluding control frames.

Useful? React with 👍 / 👎.

}
if (b1 & 0x80) off += 4; // server frames are unmasked; skip mask if set
if (this.buffer.length < off + len) return;
Expand All @@ -630,9 +655,11 @@ class AppServerClient {
return;
}
this.fragments.push(payload);
this.fragmentBytes += payload.length;
if (!fin) continue;
const text = Buffer.concat(this.fragments).toString('utf-8');
this.fragments = [];
this.fragmentBytes = 0;
this.onMessage(text);
}
}
Expand Down
83 changes: 76 additions & 7 deletions bin/codex-proxy.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import { fileURLToPath } from 'node:url';
const binDir = path.dirname(fileURLToPath(import.meta.url));

const STUB = `#!/bin/sh
if [ "$1" = "debug" ] && [ "$2" = "models" ]; then
printf '%s\\n' '{"models":[{"slug":"gpt-6.1-sol","display_name":"GPT-6.1 Sol","supported_reasoning_levels":[{"effort":"low"},{"effort":"medium"},{"effort":"high"}],"default_reasoning_level":"medium"},{"slug":"gpt-6-astra","display_name":"GPT-6 Astra","supported_reasoning_levels":[{"effort":"low"},{"effort":"medium"},{"effort":"high"}],"default_reasoning_level":"medium"},{"slug":"gpt-6-sol","display_name":"GPT-6 Sol","supported_reasoning_levels":[{"effort":"low"},{"effort":"medium"},{"effort":"high"}],"default_reasoning_level":"medium"}]}'
exit 0
fi
prompt="$(cat)"
resume=0
for a in "$@"; do [ "$a" = "resume" ] && resume=1; done
Expand Down Expand Up @@ -86,25 +90,43 @@ esac
// agentMessage deltas, token usage, turn/completed. Behaviour is keyed on
// markers in the turn text, mirroring the exec stub.
// ---------------------------------------------------------------------------
const wsServerFrame = (text) => {
const data = Buffer.from(text);
const MAX_APP_SERVER_FRAME_BYTES = 1024 * 1024;

const wsServerFrame = (text, { fin = true, opcode = 0x1 } = {}) => {
const data = Buffer.isBuffer(text) ? text : Buffer.from(text);
const first = (fin ? 0x80 : 0) | opcode;
let header;
if (data.length < 126) {
header = Buffer.from([0x81, data.length]);
} else {
header = Buffer.from([first, data.length]);
} else if (data.length <= 0xffff) {
header = Buffer.alloc(4);
header[0] = 0x81; header[1] = 126; header.writeUInt16BE(data.length, 2);
header[0] = first; header[1] = 126; header.writeUInt16BE(data.length, 2);
} else {
header = Buffer.alloc(10);
header[0] = first; header[1] = 127; header.writeBigUInt64BE(BigInt(data.length), 2);
}
return Buffer.concat([header, data]);
};

const wsServerLengthHeader = (length) => {
const header = Buffer.alloc(10);
header[0] = 0x81;
header[1] = 127;
header.writeBigUInt64BE(BigInt(length), 2);
return header;
};

const createFakeAppServer = () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codex-as-test-'));
const socketPath = path.join(dir, 'app-server-control.sock');
const requests = [];
const sockets = new Set();
const server = net.createServer((sock) => {
sockets.add(sock);
// The proxy intentionally destroys the daemon socket on invalid framing.
sock.on('error', (err) => {
if (err.code !== 'EPIPE' && err.code !== 'ECONNRESET') throw err;
});
sock.on('close', () => sockets.delete(sock));
let buf = Buffer.alloc(0);
let headersDone = false;
Expand All @@ -130,6 +152,26 @@ const createFakeAppServer = () => {
return;
}
sendObj({ id: msg.id, result: { turn: { id: 'stub-turn-1' } } });
if (text.includes('ASOVERSIZEDFRAME')) {
sock.write(Buffer.concat([
wsServerLengthHeader(BigInt(MAX_APP_SERVER_FRAME_BYTES) + 1n),
wsServerFrame(JSON.stringify({ method: 'turn/completed', params: { threadId: msg.params.threadId, turn: { id: 'stub-turn-1', status: 'completed' } } }))
]));
return;
}
if (text.includes('ASUNSAFEFRAME')) {
sock.write(wsServerLengthHeader(BigInt(Number.MAX_SAFE_INTEGER) + 1n));
return;
}
if (text.includes('ASFRAGMENTOVER')) {
const first = Buffer.alloc(600 * 1024, 0x61);
const second = Buffer.alloc(MAX_APP_SERVER_FRAME_BYTES - first.length + 1, 0x61);
sock.write(Buffer.concat([
wsServerFrame(first, { fin: false, opcode: 0x1 }),
wsServerFrame(second, { fin: true, opcode: 0x0 })
]));
return;
}
if (text.includes('ASKILL')) {
// Daemon dies mid-turn: destroy the connection with no completion.
setTimeout(() => { for (const s2 of sockets) s2.destroy(); }, 20);
Expand Down Expand Up @@ -238,10 +280,11 @@ const startProxy = async (reuse, extraEnv = {}, seedHome = null) => {
return { port, tmp, home, stateHome, stop: () => child.kill('SIGKILL'), log: () => log };
};

const post = (port, body) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
const post = (port, body, options = {}) => fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
body: JSON.stringify(body),
...options
});

const assertFailure = async (port, marker, detail) => {
Expand Down Expand Up @@ -561,6 +604,32 @@ test('app-server turn failure falls back to exec and still answers (#480)', asyn
assert.equal(JSON.parse(await res.text()).choices[0].message.content, 'Hello world');
});

for (const [marker, description, diagnostic] of [
['ASOVERSIZEDFRAME', 'oversized claimed frame closes before a following valid frame is consumed', 'app-server frame length 1048577 exceeds 1048576-byte limit'],
['ASUNSAFEFRAME', 'non-safe 64-bit frame length is rejected', 'app-server frame length 9007199254740992 exceeds 1048576-byte limit'],
['ASFRAGMENTOVER', 'fragmented message exceeding the cap is rejected', 'app-server message length 1048577 exceeds 1048576-byte limit']
]) {
test(`app-server ${description} and falls back to exec (#1839)`, async (t) => {
const fake = await createFakeAppServer();
t.after(fake.close);
const { port, stop, log } = await startProxy(null, AS_ENV(fake));
t.after(stop);
let res;
let body;
try {
res = await post(port, {
messages: [{ role: 'user', content: `please ${marker} now` }]
}, { signal: AbortSignal.timeout(5000) });
body = await res.text();
} catch (err) {
throw new Error(`${err.message}; fake requests=${JSON.stringify(fake.requests)}; proxy log=${log()}`);
}
assert.equal(res.status, 200, 'invalid framing must close the app-server and trigger exec fallback');
assert.equal(JSON.parse(body).choices[0].message.content, 'Hello world');
assert.ok(log().includes(diagnostic), `close reason should name claimed size and cap: ${log()}`);
});
}

test('app-server RPC failure falls back to exec and still answers (#480)', async (t) => {
const fake = await createFakeAppServer();
t.after(fake.close);
Expand Down