Repository navigation
Expand file tree
/
Copy pathproxy.py
More file actions
345 lines (305 loc) · 12.6 KB
/
Copy pathproxy.py
File metadata and controls
345 lines (305 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
"""
codex-inject-proxy — a tiny localhost router that lets Codex Desktop / Codex CLI
use custom (injected) models *alongside* the native ChatGPT-account models.
How it works:
- You point Codex's built-in OpenAI provider at http://127.0.0.1:8789/v1
(openai_base_url in ~/.codex/config.toml). Your ChatGPT OAuth login,
account card and usage limits stay fully stock.
- For every POST /v1/responses the proxy peeks at "model" in the JSON body:
* model listed in routes.json -> forwarded to that model's upstream
gateway, with the upstream's own API key (your OpenAI token is NOT
leaked to third parties);
* anything else -> transparent passthrough to the ChatGPT Codex
backend (chatgpt.com/backend-api/codex), headers untouched.
Single file, no framework: Python stdlib + `zstandard`
(Codex compresses request bodies with zstd, we must decompress to read
the model name; gzip is handled too).
Tested on Windows 11 with Codex Desktop; the proxy itself is portable Python.
"""
import gzip
import io
import json
import os
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from http.client import HTTPSConnection, HTTPConnection
try:
import zstandard as zstd
except ImportError:
zstd = None # zstd bodies will be logged and passed through unrouted
__version__ = "1.0.0"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROUTES_FILE = os.path.join(BASE_DIR, "routes.json")
LISTEN_HOST = "127.0.0.1"
LISTEN_PORT = 8789 # overridable via "_settings" in routes.json
UPSTREAM_OPENAI = "chatgpt.com" # ChatGPT Codex backend host
OPENAI_PREFIX = "/backend-api/codex" # /v1/X -> /backend-api/codex/X
TIMEOUT = 600
CHUNK = 65536
HOP_BY_HOP = {
"host", "content-length", "connection", "keep-alive", "proxy-authenticate",
"proxy-authorization", "te", "trailer", "trailers", "transfer-encoding", "upgrade",
"content-encoding", # request bodies are decompressed at ingress, forwarded as plain JSON
}
RESP_SKIP = {"transfer-encoding", "connection", "content-length", "content-encoding", "keep-alive"}
LOG_FILE = os.path.join(BASE_DIR, "proxy.log")
def log_line(msg):
line = "%s %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
print(line, flush=True)
try:
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
except OSError:
pass
# --------------------------------------------------------------------------
# routes.json — model-name -> upstream mapping, hot-reloaded on change.
#
# {
# "_settings": {"listen_port": 8789},
# "vendor/model-name": {
# "base_url": "https://gateway.example.com/v1",
# "api_key": "sk-..."
# }
# }
# --------------------------------------------------------------------------
_routes_cache = {"mtime": None, "routes": {}}
def load_routes():
"""Read routes.json; re-read automatically whenever the file changes."""
try:
mtime = os.path.getmtime(ROUTES_FILE)
except OSError:
mtime = None
if mtime == _routes_cache["mtime"]:
return _routes_cache["routes"]
routes = {}
try:
with open(ROUTES_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
settings = data.pop("_settings", {}) if isinstance(data, dict) else {}
if isinstance(settings, dict) and settings.get("listen_port"):
# applied at startup only; noted here for completeness
pass
routes = {k: v for k, v in data.items()
if isinstance(v, dict) and v.get("base_url") and v.get("api_key")}
log_line("loaded %d inject route(s): %s" % (len(routes), ", ".join(routes) or "-"))
except Exception as e:
log_line("routes.json load error: %r" % e)
_routes_cache["mtime"] = mtime
_routes_cache["routes"] = routes
return routes
def read_listen_port():
try:
with open(ROUTES_FILE, "r", encoding="utf-8") as f:
data = json.load(f)
port = int(data.get("_settings", {}).get("listen_port", 0))
if 0 < port < 65536:
return port
except Exception:
pass
return LISTEN_PORT
def copy_request_headers(handler, strip_auth=False, extra=None):
out = {}
for k, v in handler.headers.items():
lk = k.lower()
if lk in HOP_BY_HOP:
continue
if strip_auth and lk == "authorization":
continue
if lk == "accept-encoding":
continue
out[k] = v
out["Accept-Encoding"] = "identity"
if extra:
out.update(extra)
return out
def stream_response(handler, upstream_resp):
"""Relay upstream response to the client (SSE / chunked / fixed-length)."""
status = upstream_resp.status
headers = upstream_resp.getheaders()
hdr = {k.lower(): v for k, v in headers}
use_chunked = "chunked" in hdr.get("transfer-encoding", "").lower()
content_length = hdr.get("content-length")
handler.send_response(status)
for k, v in headers:
if k.lower() in RESP_SKIP:
continue
handler.send_header(k, v)
if use_chunked:
handler.send_header("Transfer-Encoding", "chunked")
elif content_length is not None:
handler.send_header("Content-Length", content_length)
else:
handler.send_header("Connection", "close")
handler.close_connection = True
handler.end_headers()
remaining = None
if content_length is not None and not use_chunked:
try:
remaining = int(content_length)
except ValueError:
remaining = None
while True:
if remaining is not None:
if remaining <= 0:
break
block = upstream_resp.read(min(CHUNK, remaining))
if not block:
break
remaining -= len(block)
else:
block = upstream_resp.read(CHUNK)
if not block:
break
if use_chunked:
handler.wfile.write(("%x\r\n" % len(block)).encode("ascii"))
handler.wfile.write(block)
handler.wfile.write(b"\r\n")
else:
handler.wfile.write(block)
handler.wfile.flush()
if use_chunked:
handler.wfile.write(b"0\r\n\r\n")
handler.wfile.flush()
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
timeout = TIMEOUT
def log_message(self, fmt, *args): # silence default stderr access log
pass
def _handle(self):
t0 = time.time()
parsed = urllib.parse.urlsplit(self.path)
path = parsed.path
query = ("?" + parsed.query) if parsed.query else ""
if path == "/health":
body = b'{"ok":true}'
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
# Instant local 405 for WebSocket upgrade attempts so the client
# falls back to plain HTTPS immediately (we don't proxy websockets).
if "websocket" in (self.headers.get("Upgrade") or "").lower():
log_line("%s %s websocket-upgrade -> local 405 (https fallback)" % (self.command, path))
payload = b'{"detail":"Method Not Allowed"}'
self.send_response(405)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
return
# ---- read request body (Codex may use chunked transfer encoding)
length = int(self.headers.get("Content-Length") or 0)
if "chunked" in (self.headers.get("Transfer-Encoding") or "").lower():
chunks = []
while True:
size_line = self.rfile.readline(65536).strip()
try:
size = int(size_line.split(b";")[0], 16)
except ValueError:
break
if size == 0:
while True: # consume trailers
t = self.rfile.readline(65536)
if t in (b"\r\n", b"\n", b""):
break
break
chunks.append(self.rfile.read(size))
self.rfile.read(2) # trailing CRLF after each chunk
body = b"".join(chunks)
else:
body = self.rfile.read(length) if length else b""
# ---- Codex compresses request bodies (zstd, sometimes gzip)
ce = (self.headers.get("Content-Encoding") or "").lower()
if body and "zstd" in ce:
if zstd is not None:
try:
dctx = zstd.ZstdDecompressor()
with dctx.stream_reader(io.BytesIO(body)) as zr:
body = zr.read()
except Exception as e:
log_line("WARN zstd decompress failed: %r" % e)
else:
log_line("WARN zstd-encoded body but 'zstandard' module is not installed")
elif body and "gzip" in ce:
try:
body = gzip.decompress(body)
except Exception as e:
log_line("WARN gzip decompress failed: %r" % e)
# ---- strip the /v1 prefix: both the upstream base_url and the
# ChatGPT backend prefix already replace it
fwd_path = path
if fwd_path.startswith("/v1/"):
fwd_path = fwd_path[3:]
elif fwd_path == "/v1":
fwd_path = ""
# ---- routing decision: injected model or native passthrough
model = None
route = None
if path.endswith("/responses") and body:
try:
model = json.loads(body).get("model")
route = load_routes().get(model)
except Exception:
pass
try:
if route is not None:
# inject route -> upstream gateway with its own API key
base = urllib.parse.urlsplit(route["base_url"].rstrip("/"))
use_https = (base.scheme or "https") == "https"
host = base.hostname
port = base.port or (443 if use_https else 80)
up_path = base.path + fwd_path + query
headers = copy_request_headers(self, strip_auth=True,
extra={"Authorization": "Bearer " + route["api_key"],
"Host": host})
conn = (HTTPSConnection if use_https else HTTPConnection)(host, port, timeout=TIMEOUT)
where = "inject:%s" % host
else:
# passthrough -> ChatGPT Codex backend, headers (OAuth!) untouched
up_path = OPENAI_PREFIX + fwd_path + query
headers = copy_request_headers(self, strip_auth=False,
extra={"Host": UPSTREAM_OPENAI})
conn = HTTPSConnection(UPSTREAM_OPENAI, 443, timeout=TIMEOUT)
where = "openai-passthrough"
conn.request(self.command, up_path, body=body if body else None, headers=headers)
resp = conn.getresponse()
ms = int((time.time() - t0) * 1000)
log_line("%s %s model=%s -> %s status=%d %dms"
% (self.command, path, model or "-", where, resp.status, ms))
stream_response(self, resp)
conn.close()
except Exception as e:
ms = int((time.time() - t0) * 1000)
log_line("%s %s model=%s ERROR %r %dms" % (self.command, path, model or "-", e, ms))
try:
payload = json.dumps({"error": {"message": "inject-proxy: %r" % e,
"type": "proxy_error"}}).encode()
self.send_response(502)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
except Exception:
pass
do_GET = _handle
do_POST = _handle
do_PUT = _handle
do_DELETE = _handle
do_PATCH = _handle
class Server(ThreadingHTTPServer):
# On Windows SO_REUSEADDR would let a second instance silently share the port
allow_reuse_address = False
daemon_threads = True
if __name__ == "__main__":
port = read_listen_port()
load_routes()
server = Server((LISTEN_HOST, port), Handler)
log_line("codex-inject-proxy v%s listening on http://%s:%d" % (__version__, LISTEN_HOST, port))
try:
server.serve_forever()
except KeyboardInterrupt:
pass