Case Study/AI & Agents/Design, engineering, maintenance

OpenAI-Compatible Session Gateway

Author
Aryan
Client
Private AI platform
Published
2026
Length
8 min · 1765 words

Abstract

Self-hosted gateway that pools encrypted sessions behind one OpenAI-compatible API.

Key outcomes

API
OpenAI-compatible
Runtime
Zero browser overhead
Pool
AES-256-GCM

Why a gateway instead of a wrapper

The upstream platform has no public API. It is a web product with session cookies, a signed request scheme and a set of internal endpoints, and any integration against it has to speak that protocol directly. The obvious approach is to write a small wrapper at each caller: the bot handles its own cookies, its own request signing, its own retries and its own failure modes, and the next caller writes the same thing again with different bugs.

The gateway exists to centralise that. One process owns the session lifecycle, exposes an API shape callers already understand, and pools capacity behind it. Callers never see a cookie, a signature or a device identifier; they see a base URL and an API key.

That inversion also decides where the hard problems live. Because the surface is a single service, account health, cookie rotation and signing are solved once, in a place where they can be observed and repaired, instead of being duplicated across every consumer.

The signing problem, and why browser automation is the wrong tool

Every request to the platform carries a signature, produced by a pair of parameters that are generated by vendor code and documented nowhere. Reimplementing them from scratch would mean reverse-engineering an algorithm that changes without notice and breaking whenever it does.

The common workaround is to drive a real browser, launching headless Chrome per request so the vendor’s own JavaScript generates the signature. That workaround carries three costs at once. It is slow, because browser startup dominates every request. It is memory-heavy, because each instance is hundreds of megabytes. And it is fragile in a specific way, because it depends on a page that the front end can redeploy at any time, which means a change that has nothing to do with the API can break every call.

The alternative here is to run only the signing code, not the browser around it. The signature is produced by the vendor’s signer directly, involving SM3, RC4 and a custom base64 variant, and the result is fed into the outgoing request. The algorithm stays vendor-owned, which means a rotation on their side is a file update rather than a rewrite.

Keeping the signer in its own process

The signer is Python and the gateway is Bun, and the boundary between them is deliberate rather than incidental. A persistent Python worker runs the vendored signer, and the Bun side communicates with it over stdin and stdout, so the HTTP layer and the request layer stay in one runtime while the vendor code stays untouched.

The reason for a process boundary rather than a port is isolation. The signer is opaque vendor code handling hostile input on the request path. If it crashes, or throws on a payload the API layer would otherwise handle, the worker dies and is restarted while the gateway keeps serving. Putting that code in the same process would let a signing failure take down the whole service, which is a bad trade for the convenience of avoiding serialization.

The cost of the boundary is real: parameters are marshalled across a pipe, and the worker needs supervision so a wedged process does not silently stall every request. That supervision is worth the alternative, which is a shared failure domain between a web framework and reverse-engineered vendor code.

Pooling sessions, and encrypting them at rest

A single upstream session has limits, and rate limits and daily quotas make one session insufficient for sustained traffic. The gateway therefore manages a pool. Multiple cookie sessions are imported, either as a Cookie-Editor JSON array or a raw Cookie: header string, and each becomes an account in the pool.

Those cookies are encrypted at rest with AES-256-GCM, using a key seeded into a local secret file on first boot. A session cookie is a full credential, equivalent to a logged-in browser, so storing the pool as plaintext would make the database file a credential dump. Encryption at rest is the minimum for a file that gets copied around during backup and debugging.

Requests are distributed round-robin across enabled accounts. Failure handling is automatic rather than manual: an account that fails repeatedly is disabled after a small threshold, and the failure count is the same path the maintenance loop uses to demote accounts. Re-enabling is a dashboard action, so a bad account cannot quietly return to the rotation because its next probe happened to succeed once.

Two details matter for correctness. Device identifiers can be extracted from a captured request URL when one is supplied, or generated when it is not, because some endpoints expect consistent identifiers across calls from the same account. And accounts are selected per request, so a caller that needs a specific account can name it rather than accept whichever one the rotation picks.

Session maintenance as a background job

The interesting part of running on pasted cookies is that they do not stay valid. Upstream rotates short-lived values constantly, and refuses to serve a session whose values have gone stale.

Rather than asking operators to re-import cookies, the gateway absorbs rotation the same way a browser does. Every upstream response is scanned for Set-Cookie, and refreshed values are merged back into the account’s encrypted store. That is the mechanism the web client itself relies on, so it tracks the platform’s behaviour rather than fighting it.

On top of that a maintenance loop runs in the background, first shortly after boot and then on a fixed interval. Each pass validates every enabled account, demotes the ones that fail through the normal failure path, and re-enables disabled accounts whose sessions have recovered. There are separate controls for the probe delay and the number of failed probes before giving up, because aggressive reprobing wastes upstream tolerance and passive reprobing leaves capacity idle. One value is refreshed on its own daily schedule against the vendor’s token endpoint, since it has a different clock than the rest.

There are limits, and they are worth stating plainly. A session that has been fully logged out cannot be repaired by rotation; it requires a real login and a re-import. The longest-lived cookie in the set has a lifetime measured in weeks, so an account that goes untouched long enough will eventually need attention. The maintenance loop reduces that to an occasional event rather than a routine chore, and the dashboard surfaces which accounts are near the end.

The OpenAI-shaped surface

The API is deliberately modelled on OpenAI’s, because callers already have clients for that shape, even though the platform underneath speaks its own protocol. A base URL swap is a smaller change than a bespoke client, and it means an upstream model abstraction does not have to know that this backend exists.

Chat completions support both streaming and non-streaming responses, with a conversation identifier carried in the request and returned in the response so multi-turn threads can be addressed explicitly rather than reconstructed from message history. Model listing, conversation listing and per-conversation message history cover the read side, since inspecting what was said earlier is part of using the platform, not an afterthought.

File upload is multipart and returns a reference rather than a blob, which is then attached to a chat request by identifier. Video generation is asynchronous by nature: submission returns an id with a queued status, and a separate poll endpoint reports progress and, on completion, a download URL. The distinction matters because a video job can run for minutes, and holding an HTTP connection open for that is the wrong shape for a gateway that is also serving chat.

One detail is deliberate rather than cosmetic. Upstream returns video links with a watermark rule and a download flag, including inside conversation text when an agent produced the video. The gateway rewrites those to the plain playback form so the link previews inline without a watermark overlay, because exposing the raw URL would hand callers a link that behaves differently depending on where it came from.

Quota and cost as first-class concerns

Video generation is the expensive operation, and upstream gates it per account per day. That makes quota a property of the pool, not of a request. The account list surfaces remaining video quota, so an operator can see which accounts are spendable before a job fails, and there is an explicit reset action for the cases where upstream has reset the count but the local view has not caught up.

A media job log records video and media work across all accounts, filterable by account, status, kind and query, which turns “which account burned the quota and on what” into a lookup rather than an investigation. This is the part that tends to be missing from proxy implementations: they handle the happy path and leave operators guessing about capacity.

Operating the pool

The dashboard exists so that running the pool does not require the CLI. It covers account import, validation and enablement, API key issuance, per-account rotation and cookie reset, quota resets, a per-request log and the media log. Request logs are the debugging surface, because the failure modes here are upstream-shaped and the only way to explain them is to see what was actually sent and what came back.

Deployment is a container with a mounted data volume and a secret supplied through the environment. Cookies, the database, the encryption key and issued API keys all live under that volume, which is the only state the service has. A development mode that skips authentication exists for local work, and is the kind of switch that has to be obviously off in production rather than merely unset.

What was hard, and what I would do differently

The hardest constraint is that the protocol is owned by someone else. The signer works for the parameters being sent, but if the algorithm rotates, the only correct response is to update the vendored signer, and there is no way to design around that dependency. Living with it means keeping the signer isolated so the update is small and local, which is exactly why it is a separate process running an unmodified vendor file.

The second lesson is about observability. Health was initially inferred from request success, which meant a broken account looked like normal traffic loss until enough failures accumulated. Making account state visible, with last validation time and failure count on the dashboard, turned a mysterious degradation into a single glance. If rebuilding this, I would add that from the first commit rather than after the first unexplained outage.

References

  1. [Author]Aryan (Uo1428)

Built with

BunHonobun:sqliteReactVitePython

Related production systems from the same category.

All case studies →

Want this kind of system on your side of the table?