# Build "clay": a private relay for Claude Code and Codex

You are building a small, production-quality program from this specification.
Read all of it before writing code. Where it says MUST, it is a requirement
with an acceptance test; where it says "suggested", use your judgement.

Before relying on anything marked **[verify]**, confirm it against the
current source or observed traffic of the tool named: provider details drift,
and a stale value fails silently.

**Terms of use.** Using a consumer subscription (Claude Pro/Max, ChatGPT)
through a relay, and presenting a different location to the provider, may be
restricted by the provider's terms. Read the current terms for every account
you put behind the relay before you deploy it. This specification is for one
person relaying their own accounts to their own machines.

---

## 1. What it is

clay is one binary and one config file. It runs on one server inside the
user's Tailscale tailnet. The user's other machines point Claude Code and
Codex at it; it forwards their requests to Anthropic or OpenAI with
credentials that live only on the server.

What it gives:

- **One place for credentials.** Client machines hold no secret and need no
  sign-in.
- **Several accounts per route.** When one is rate limited, the next serves
  the request without the client noticing.
- **Tailnet only.** It listens only on a tailnet or loopback address and
  serves only listed tailnet machines; a typo cannot expose it.
- **The provider sees the server.** Requests leave from the server's address,
  and an optional setting presents a fixed time zone instead of each
  machine's own.

Non-goals (do not build): multiple users or tenants, an admin UI, a database,
API translation between providers, request caching, load balancing across
accounts (accounts are an ordered fallback list, not a pool), any listener
outside the tailnet.

Requests pass through as the client sent them. clay is a careful reverse
proxy, not a gateway.

## 2. Fixed decisions

| Area            | Decision                                                                                                                                                     |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Language        | Suggested: Go, standard library plus one TOML parser. Any language is acceptable if it yields one static binary and streams without buffering.               |
| Process         | `clay serve -config <path>`, run by systemd as an unprivileged `clay` user.                                                                                  |
| Config          | One TOML file. Unknown keys MUST be errors, so a misspelt key is reported, not ignored.                                                                      |
| State           | Credentials in `<state_dir>/accounts/<name>.json`, mode 0600, written atomically (temp file, fsync, rename). No database.                                    |
| Network         | Bind to exactly one IP: a Tailscale address (100.64.0.0/10 or fd7a:115c:a1e0::/48) or loopback. Refuse `0.0.0.0`, `::`, LAN and public addresses.            |
| Auth of clients | By TCP source address only (Tailscale has authenticated the machine). No client keys.                                                                        |
| Reload          | SIGHUP re-reads config and credentials. An invalid file is refused and the running config stays. `listen` changes need a restart.                            |
| Logs            | JSON to stdout, one line per request, plus lifecycle lines. Never log credential values, even in errors about malformed input.                               |
| Versioning      | `clay version` prints the version and the VCS commit the binary was built from (12 hex chars), with `+modified` if the tree was dirty. Also logged at start. |

## 3. Configuration

```toml
listen = "100.64.0.1:8787"          # required; tailnet or loopback IP + port
# state_dir = "/var/lib/clay"       # optional; absolute path
# timezone = "America/Los_Angeles"  # optional; IANA name; "Local" refused

[[client]]                          # at least one
name = "laptop"                     # [a-z0-9-]+, unique
addr = "100.64.0.2"                 # an IP, or a CIDR such as "100.64.0.0/10"

[[route]]                           # at least one
prefix = "/claude"                  # "/" + [a-z0-9-]+; not /healthz or /status
# upstream = "https://..."          # optional; must be https; default by kind
  [[route.account]]                 # at least one per route; order matters
  name = "claude-1"                 # [a-z0-9-]+, unique across all routes
  kind = "claude-setup-token"
  switch_at = 0.95                  # optional; claude-setup-token only; (0, 1]
```

Account kinds:

| kind                 | Default upstream                        | Credential                                | API family |
| -------------------- | --------------------------------------- | ----------------------------------------- | ---------- |
| `claude-setup-token` | `https://api.anthropic.com`             | token from `claude setup-token`           | Anthropic  |
| `anthropic-api-key`  | `https://api.anthropic.com`             | Anthropic API key                         | Anthropic  |
| `codex-chatgpt`      | `https://chatgpt.com/backend-api/codex` | a Codex CLI ChatGPT sign-in (`auth.json`) | Codex      |
| `openai-api-key`     | `https://api.openai.com/v1`             | OpenAI API key                            | OpenAI     |

Validation (all MUST, each with a test; errors name the offending key):

- every address, including each `[[client]]` addr and the `listen` IP, lies
  within the Tailscale ranges or loopback;
- names unique and well formed; prefixes unique and well formed;
- all accounts in a route share one API family;
- `switch_at` only on `claude-setup-token`, in (0, 1];
- `upstream` parses as an https URL;
- `timezone` loads as an IANA zone.

Client matching: a request's source address is matched against `[[client]]`
entries **in file order; the first match names it**. Document that single
machines must be listed before a wide prefix, or they are all logged under the
prefix's name.

## 4. HTTP behaviour

| Path                          | Who                               | Response                                                 |
| ----------------------------- | --------------------------------- | -------------------------------------------------------- |
| `GET /healthz`                | anyone who can reach the listener | `ok`                                                     |
| `GET /status`                 | configured clients only           | JSON: every route and account with its state (section 6) |
| `/<prefix>/<rest>`            | configured clients only           | proxied to `<upstream>/<rest>?<same query>`              |
| anything else                 | configured clients                | 404 with a JSON error naming the problem                 |
| any, from an unlisted address |                                   | 403 JSON: `source address is not a configured client`    |

Errors the relay generates itself use one shape on every route,
`{"type":"error","error":{"type":"<kind>","message":"clay: <text>"}}`: both
Anthropic and OpenAI clients read `error.message`, so they display it. Kinds
used: `forbidden` (403), `not_found` (404), `bad_request`,
`request_too_large` (413), `rate_limit_error` (429), `relay_unavailable`
(503), `upstream_unreachable` and `upstream_error` (502).

### Request headers

- Pass the client's headers through, including `User-Agent` (if the client
  sent none, send none; do not add the runtime's default).
- Remove: `Authorization`, `X-Api-Key`, `Cookie`, `Accept-Encoding`,
  `Forwarded`, `X-Forwarded-*`, `X-Real-Ip`, `Chatgpt-Account-Id`,
  `Openai-Organization`, `Openai-Project`, and hop-by-hop headers (including
  any named in `Connection`).
- Add the account's credential:

| kind                 | Headers set                                                                                                                                                                                                                                               |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `claude-setup-token` | `Authorization: Bearer <token>`; `Anthropic-Version: 2023-06-01` if absent; `Anthropic-Beta` with the OAuth beta **first**, then the client's betas deduplicated. The OAuth beta was `oauth-2025-04-20` **\[verify against Claude Code's own requests]**. |
| `anthropic-api-key`  | `X-Api-Key: <key>`; `Anthropic-Version` if absent                                                                                                                                                                                                         |
| `codex-chatgpt`      | `Authorization: Bearer <access token>`; `Chatgpt-Account-Id: <account id>`                                                                                                                                                                                |
| `openai-api-key`     | `Authorization: Bearer <key>`                                                                                                                                                                                                                             |

### Response headers

Pass back everything except `Set-Cookie` and hop-by-hop headers.

### Body and streaming

- Request body limit 32 MiB (413 above). Buffer the request body (needed for
  retries on another account), never the response.
- Stream responses (SSE included) to the client as they arrive: flush after
  every write. A test MUST show the first event reaches the client before the
  upstream finishes.
- Timeouts: 10 minutes for the provider to start answering (then 502); 5
  minutes of silence in either direction cuts the transfer and logs it. No
  overall deadline: long streams are normal.
- On shutdown (SIGTERM), stop accepting, and give running responses up to 5
  minutes to finish.

## 5. Choosing an account (the core rule)

Accounts in a route are tried in listed order. The relay moves to the next
account **only** when the current one answered 429, 529, 401 or 403, **and
only before any byte of the response has been sent to the client**.

A 5xx, a timeout or a broken connection is returned to the client as it is and
never retried: the provider may already have executed the request, and
retrying could run it twice. When the last account is rate limited, the
client receives that provider's own answer (status, headers, body).

Resting:

- An account answered 429/529 rests until `Retry-After`, or 1 minute if none
  was given. A 401/403 rests it for 5 minutes (a Codex 401 first triggers one
  renewal; see section 7). Resting accounts are skipped.
- If every account on the route is resting, the relay answers 429
  `rate_limit_error` itself, with `Retry-After` set to when the earliest one
  returns. If no account can serve at all (e.g. every one is `needs_login`),
  it answers 503 `relay_unavailable`.
- **Per-model rests** (Anthropic routes): a 429 rests only the requested model
  on that account (the model is read from the request JSON's `model` field),
  unless the provider's rate-limit headers say an account-wide limit was hit,
  in which case the whole account rests. Subscriptions have model-scoped
  weekly limits; one model running out must not take the account away from
  the others. Cap the number of resting models per account, dropping the one
  ending soonest.

`switch_at` (Claude subscriptions): Anthropic reports usage in response
headers of the form `Anthropic-Ratelimit-Unified-<family>-Utilization`,
`-Status` and `-Reset` **\[verify the header names in a real response]**.
Record the latest per account. Once a limit that applies to the request's
model is at or past `switch_at`, try accounts still below it first. It is a
preference, never a refusal: if every account is past it, use listed order
(which may spend a paid key listed last). Log the passed-over accounts in a
`deferred` field.

## 6. Status

`/status` shows each account as one of:

| state         | meaning                                                                       |
| ------------- | ----------------------------------------------------------------------------- |
| `ready`       | usable                                                                        |
| `resting`     | rate limited or refused; includes when it returns and why                     |
| `needs_login` | a Codex sign-in the provider will no longer renew; a human must sign in again |

Claude subscription accounts also show `limits` (latest utilization 0–1,
status and reset per limit family), `model_rests`, and `switch_at`.

## 7. Credentials

Commands, all run as the `clay` user:

- `clay import-token -account <name>`: reads a token or API key from stdin
  (no echo when stdin is a terminal) and writes the account file.
- `clay import-codex -account <name> <path/to/auth.json>`: imports a Codex
  CLI ChatGPT sign-in. Refuse an API-key `auth.json`. Check that the account
  id in the file agrees with the one inside the access token.
- `clay check`: validates the config and loads every credential; non-zero
  exit on any problem; prints each account's result without secrets.

### Codex ChatGPT sign-in renewal (the part most likely to fail silently)

Implement the Codex CLI's own refresh protocol **\[verify against the
openai/codex source: login/src/auth/manager.rs for the token endpoint and
public client id, login/src/oauth/client.rs for the refresh request,
login/src/token\_data.rs for the account claim]**. At the time of writing it
is a JSON `refresh_token` grant to `https://auth.openai.com/oauth/token`.

Rules (each MUST have a test with a fake token endpoint):

1. **One refresher per sign-in.** Each renewal rotates the refresh token and
   invalidates the previous one. The relay must be the sign-in's only user.
   Document this loudly: never use that sign-in in a Codex CLI elsewhere,
   never run `codex logout` with it.
2. **Serialise renewals per account.** Concurrent requests that need a renewal
   wait for one renewal, not start several.
3. **Save before use.** Write the new tokens to disk atomically before using
   them. If saving fails, keep them in memory, keep retrying the save, and
   never fall back to the older tokens on disk.
4. **Classify failures.** Refused by the provider (e.g. `invalid_grant`):
   `needs_login`. Not sent, or a clear transient error: keep the old token,
   retry later. **Ambiguous** (sent, no answer read): the provider may have
   rotated the token; do not discard state, retry with the same refresh
   token, and only mark `needs_login` if the provider then refuses it.
5. **When to renew:** a background sweep (suggested every 15 minutes); before
   use if the access token expires within 5 minutes; once when the upstream
   answers 401, then retry that request once with the new token (only if
   nothing was sent to the client yet). Never loop.
6. On reload, adopt a newer credential file from disk, but never replace a
   newer in-memory token with an older file.

## 8. Optional: present a fixed time zone

When `timezone` is set, rewrite **only the dates and zones the client
generates**, so the request content does not reveal the client's region.
Never rewrite what the user typed.

- Anthropic routes: `Today's date is YYYY-MM-DD` in the system prompt (string
  or blocks), in `role: system` messages, and in `<system-reminder>` blocks
  inside user content. A plain user message saying the same words is left
  alone. Assistant content is left alone.
- Codex/OpenAI routes: inside `<environment_context>…</environment_context>`
  in `input_text` of `role: user` messages only: `<current_date>` and
  `<timezone>`. Text after the closing tag, other roles, and `output_text`
  are left alone. A block with no closing tag is left alone.
- The replacement date is today's date in the configured zone at the moment
  of the request.

Requirements:

- **Every byte outside the rewritten strings is preserved**: whitespace, key
  order, duplicate keys, escapes. Do not decode and re-encode the JSON; walk
  the bytes, and test that the walker agrees with a real JSON decoder on
  strings full of escapes and brackets.
- A compressed request body (`Content-Encoding` other than identity) is
  passed unchanged with a logged warning.
- Invalid or truncated JSON is passed unchanged.
- Log `tz_rewrites` (count) on lines where it is greater than 0.

The exact strings each client writes are **\[verify]**: capture a real request
from current Claude Code and Codex before trusting the patterns above.

## 9. Logs

One JSON line per request with: `client`, `route`, `account` (when one was
used), `status`, `bytes`, `ms` (total), token usage when the provider reports
it in the response (parse the SSE stream's usage events as they pass, without
buffering), `deferred`, `tz_rewrites`. Proxied requests also log:

| field            | measures                                      | large when                                                    |
| ---------------- | --------------------------------------------- | ------------------------------------------------------------- |
| `upstream_ms`    | arrival until the provider's response headers | the provider is slow to start, or earlier accounts were tried |
| `client_wait_ms` | total time blocked writing to the client      | the client's network path is slow or losing packets           |

These two separate "the provider is slow" from "the client's network is bad"
without a packet capture. Test both: a client that delays reading must show
large `client_wait_ms`; a prompt client must show near zero.

## 10. Operations

Ship:

- a systemd unit: `User=clay`, `ExecReload=/bin/kill -HUP $MAINPID`,
  `Restart=always`, `StartLimitIntervalSec=0` (at boot the tailnet address may
  not exist yet, so binding fails until Tailscale is up; keep retrying),
  `TimeoutStopSec` above the 5-minute drain, `StateDirectory=clay`,
  `UMask=0077`, and hardening (`NoNewPrivileges`, `ProtectSystem=strict`,
  `ProtectHome`, `PrivateTmp`, empty capability set, restricted address
  families);
- a fully commented example config;
- a README covering install, importing each credential kind, connecting a
  client, configuration, day-to-day commands, how requests are handled,
  troubleshooting, and security.

## 11. Client setup to document

Claude Code, in `~/.claude/settings.json` (not a shell profile: IDE
extensions and desktop apps never read the profile):

```json
{
  "env": {
    "ANTHROPIC_BASE_URL": "http://<relay>:8787/claude",
    "ANTHROPIC_AUTH_TOKEN": "unused",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
  }
}
```

- `ANTHROPIC_AUTH_TOKEN` must be set or Claude Code asks to sign in; the
  relay replaces it.
- The traffic flag stops Claude Code's direct telemetry, error reports and
  update checks, which otherwise leave from the client's own address. It also
  stops auto-update (update with `claude update`).
- For a machine that should use the relay only sometimes: put the block in a
  separate profile directory (e.g. `~/.claude-relay/settings.json`) and a
  launcher script that sets `CLAUDE_CONFIG_DIR` to it and execs `claude`.

Codex, in `~/.codex/config.toml` (`model_provider` must be above every table):

```toml
model_provider = "clay"

[model_providers.clay]
name = "clay"
base_url = "http://<relay>:8787/codex"
wire_api = "responses"
supports_websockets = false

[analytics]
enabled = false   # otherwise Codex contacts chatgpt.com directly
```

State in the docs what the provider can still see through the relay: working
directory and home path, OS and architecture, `CLAUDE.md`/`AGENTS.md`
contents, and a stable per-machine id. The relay hides where a machine is,
not which machine it is.

## 12. Traps already paid for

Put each in the troubleshooting docs:

- A tailnet ACL that blocks a machine shows as a **timeout**, not a 403: the
  packet never arrives. Check the ACL before the relay config.
- First-match client naming (section 3).
- Slow replies or `Connection lost mid-response` with large `client_wait_ms`
  means packet loss between client and relay (a router or VPN on the path is
  the usual cause). `tailscale ping --size <n> <relay>` across sizes finds
  sizes that never arrive; forcing traffic through a DERP relay is a
  workaround.
- A reply in a client does not prove the relay carried it: a missed setting
  sends the request straight to the provider. The relay's log line for that
  client is the only proof.
- Two Codex refreshers on one sign-in invalidate each other, and show up hours
  later as `needs_login`.

## 13. Build order

Do not start a phase until the previous phase's tests pass (with the race
detector, if the language has one).

1. **Config**: parse, validate, defaults; table-driven tests for every rule.
2. **Proxy core**: listener, client admission, `/healthz`, routing, header
   rules, streaming, limits, timeouts, graceful shutdown. Test against a fake
   upstream (an in-process HTTP server).
3. **Accounts**: ordered fallback, the only-before-first-byte rule, no retry on
   5xx, resting, per-model rests, `switch_at`, `/status`.
4. **Credentials**: import commands, atomic files, `clay check`, Codex
   renewal with every rule in section 7 against a fake token endpoint,
   including the ambiguous-failure and save-failure cases.
5. **Time zone rewrite**: the byte-preserving walker and its cases.
6. **Observability and ops**: log fields, timing fields, `version` with
   commit, SIGHUP reload, systemd unit, example config, README.

## 14. Definition of done

Show each passing:

- [ ] Format, lint/vet, all tests (race detector on), and a Linux amd64 build
  in one script that prints a single green line.
- [ ] An end-to-end smoke test with fake upstreams and no real account: a
  configured client gets a streamed answer; an unlisted address gets 403;
  the first account returns 429 and the second serves the request; with
  every account resting the relay answers 429 with `Retry-After`; a 500
  is not retried; a reload with a bad file keeps the old config.
- [ ] `clay check` passes on the example config with dummy credentials and
  fails, naming the key, on each class of invalid config.
- [ ] No test or log line contains a credential value (grep the test output
  for the dummy secrets).
- [ ] Manual, with real accounts: `claude -p "Reply with ok."` and
  `codex exec --skip-git-repo-check "Reply with ok."` from a client both
  answer, and the relay's log shows a line for each with that client's
  name.

---

# Additional Notes

Settings that stop Claude Code and Codex sending unnecessary info to providers (from docs/installation.md, "Note: what the providers can see")

## Claude Code: in the env block of settings.json

"CLAUDE\_CODE\_DISABLE\_NONESSENTIAL\_TRAFFIC": "1"

- Without it, Claude Code connects to Anthropic directly for telemetry, error reports and update checks, even with ANTHROPIC\_BASE\_URL set. Those connections come from the machine's own network address.

- With it, there were no direct connections to Anthropic (measured on Claude Code 2.1.319).

- Side effect: automatic updates stop too, so update by hand with `claude update`.

- One GitHub connection remained, probably plugin marketplace updates. GitHub sees the machine's address, Anthropic doesn't.

- Put it in settings.json rather than a shell export, because the IDE extension and the desktop app never read your shell profile.

## Codex: in \~/.codex/config.toml

[analytics] enabled = false

- Without it, Codex connects directly to chatgpt.com and ab.chatgpt.com for analytics and metrics.

- With it, there were no direct connections, in two runs (Codex 0.167.0, clean config, no sign-in).

- Not measured: a machine with its own Codex sign-in, plugins or cloud features turned on.

## On the relay: timezone = "America/Los_Angeles" in clay.toml

- Codex writes the machine's time zone (e.g. Asia/Shanghai) into every request. Both clients write the local date.

- The relay rewrites those two values to Los Angeles, so the request content doesn't point to your region. Text you type is passed on unchanged.

## What no setting hides

- Working directory and home path, which include your user name.

- OS version, CPU architecture and the terminal program.

- The contents of CLAUDE.md or AGENTS.md.

- A stable device ID per machine (device_id for Claude Code, installation_id for Codex).

So the providers can tell your machines apart and link their sessions, but they can't place them. The accounts themselves are tied to you and to wherever each sign-in was made.

