Skip to content
Merged
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
5 changes: 4 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,10 @@ PORT=20123

# Permission ruleset applied to every API session, as a JSON array. Unset means
# the OpenCode default (build agent prompts/denies per its own policy).
# OPENCODE_AGENT_PERMISSIONS=[{"action":"*","resource":"*","effect":"allow"}]
# Deny first, then fall back to `ask`: an `allow` catch-all would grant the agent
# unrestricted tool access, so the built-in shell/web tools stay denied and
# everything else asks.
# OPENCODE_AGENT_PERMISSIONS=[{"action":"bash","resource":"*","effect":"deny"},{"action":"webfetch","resource":"*","effect":"deny"},{"action":"websearch","resource":"*","effect":"deny"},{"action":"*","resource":"*","effect":"ask"}]

# ---------------------------------------------------------------------------
# Gateway state, sticky sessions and model cache
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -522,8 +522,9 @@ Every variable, with types, defaults and security notes:
defaults. Requires a key unless `OPENCODE_METRICS_PUBLIC=true` is set **and** no
`OPENCODE_METRICS_TOKEN` is configured: a configured token is always required,
even when the endpoint is public, so a general API key is never handed to a
scraper. `/metrics` is
never rate limited, so a local scraper cannot be throttled by its own traffic.
scraper. `/metrics` is charged to the same rate-limit bucket as the API routes,
so an anonymous scraper cannot walk every collector without limit; only the
liveness probes and `OPTIONS` stay exempt.
* **`/admin/*`** — `/admin/status` (config, upstream binary and URL, catalog
counts, session count), `/admin/config` (effective configuration with API keys
and the upstream password redacted), `/admin/models/refresh`, `/admin/sessions`
Expand Down
10 changes: 6 additions & 4 deletions docs/API.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ data: {"error":{"message":"The upstream completion ended with an error.","type":
| `403` | `invalid_request_error` | `permission_error` |
| `404` | `invalid_request_error` | `model_not_found` |
| `429` | `rate_limit_error` | `provider.free-limit`, `rate_limit_error`, `rate_limit_exceeded` (the gateway's own limiter; with `retry-after` header, in seconds; mid-stream the hint travels as `retry_after_ms` in the error frame instead) |
| `499` | — | client disconnected before the response started |
| `499` | `api_error` | `timeout_error` — client disconnected before the response started |
| `501` | `invalid_request_error` | `not_implemented_error` |
| `502` | `api_error` | `upstream_error`, `upstream_invalid_json` |
| `503` | `api_error` | `overloaded_error`, `upstream_unavailable`, `upstream_unreachable`, `upstream_unauthorized` (the upstream answered `401`/`403`: check `OPENCODE_SERVER_PASSWORD`), `event_stream_unavailable`, `event_stream_lost` (a mid-turn event-stream reconnect; the answer would have been incomplete) |
Expand Down Expand Up @@ -958,9 +958,11 @@ When `OPENCODE_RATE_LIMIT_RPM` is non-zero every authenticated request is charge
against a per-key token bucket (with a separate bucket for `/admin/*`). A
rejected request answers `429` with `error.code: "rate_limit_exceeded"` and a
`retry-after` header in seconds. Failed authentication has its own always-on
bucket (at least 60 attempts per minute per client address) and also answers
`429` once it is spent. `/health`, `/ready`, `/healthz`, `/metrics` and `/`
are never rate limited.
bucket (at least 60 attempts per minute per client address) plus a much higher
global ceiling over every address, and also answers `429` once either is spent.
`/health`, `/ready`, `/healthz` and `/` are never rate limited; `/metrics` is
charged to the same bucket as any other route, so an anonymous scrape loop is
throttled too.

`OPENCODE_BODY_TIMEOUT_MS` bounds how long a caller may take to send the request
body; a request that never finishes is disconnected. It does not apply to a
Expand Down
34 changes: 25 additions & 9 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ variable. (Discovery and the spawned CLI read the variables listed in
| `HOST` | string | `127.0.0.1` | Interface the gateway binds. | Anything other than a loopback address exposes the API (and the OpenCode agent) to the network. Set `0.0.0.0` only inside a container or behind a proxy. |
| `PORT` | integer 1–65535 | `20123` | TCP port to listen on. | — |
| `OPENCODE_MAX_BODY_BYTES` | integer ≥ 1024 | `67108864` (64 MiB) | Maximum request body size. | Raising it widens the memory-exhaustion surface; base64 media inflates bodies by ~33%. |
| `OPENCODE_TRUST_PROXY` | `true`-like, `false`-like, a positive hop count, or a CSV list of trusted IPs/CIDRs | `false` | Trust `x-forwarded-*` headers for the client address. `true`/`yes`/`on`/`enabled` trusts every hop; `false`/`no`/`off`/`disabled`/`0` trusts nothing; a positive integer is a hop count (`1` trusts the immediate peer only, `2` the last two, …) and is compiled into Fastify's function form; `10.0.0.0/8,127.0.0.1` trusts only those peers. An unrecognised value warns (without echoing it) and falls back to `false`. | Enable only when a proxy you control terminates the connection and overwrites the forwarded headers; otherwise clients can spoof their address in logs, metrics **and the per-address rate-limit bucket**, which makes the anonymous limiter ineffective. Prefer a hop count or a CIDR list over a bare `true`: with `true` the leftmost `x-forwarded-for` entry is trusted even when a client prepended one. |
| `OPENCODE_TRUST_PROXY` | `true`-like, `false`-like, a positive hop count, or a CSV list of trusted IPs/CIDRs | `false` | Trust `x-forwarded-*` headers for the client address. `true`/`yes`/`on`/`enabled` trusts every hop; `false`/`no`/`off`/`disabled`/`0` trusts nothing; a positive integer is a hop count (`1` trusts the immediate peer only, `2` the last two, …) and is compiled into Fastify's function form; `10.0.0.0/8,127.0.0.1` trusts only those peers. An unrecognised value — including a CIDR with a `/0` prefix, which would trust every peer — warns (without echoing it) and falls back to `false`. | Enable only when a proxy you control terminates the connection and overwrites the forwarded headers; otherwise clients can spoof their address in logs, metrics **and the per-address rate-limit bucket**, which makes the anonymous limiter ineffective. Prefer a hop count or a CIDR list over a bare `true`: with `true` the leftmost `x-forwarded-for` entry is trusted even when a client prepended one. |
| `OPENCODE_BODY_TIMEOUT_MS` | integer ≥ 1000 | `300000` (5 min) | Wall-clock budget for receiving one request body. A caller that opens a connection and never finishes sending is disconnected when it expires. Only body receipt is bounded; a `stream: true` response is never cut short by it. | Bounds how long a caller can hold a connection and its body buffers (`OPENCODE_MAX_BODY_BYTES` each) without completing a request. Lower it if your clients never upload large media. |
| `OPENCODE_CORS_ORIGINS` | CSV list | *(empty)* | Allowed browser origins; `*` allows all. An allowed origin receives `access-control-allow-headers` covering this gateway's headers plus the ones the official OpenAI and Anthropic SDKs send (`openai-organization`, `openai-project`, `x-stainless-*`, `anthropic-dangerous-direct-browser-access`), and `access-control-expose-headers: x-request-id`. | `*` lets any web page call the gateway with a user's key. Prefer an explicit list. |
| `OPENCODE_RATE_LIMIT_RPM` | integer ≥ 0 | `0` | Sustained requests per minute allowed per authenticated API key; `0` disables this limiter. `/admin/*` uses its own separate bucket. Failed authentication is throttled by a third bucket that is always active (at least 60 failed attempts per minute per client address), independently of this variable. | Bounds how many paid upstream turns one key can trigger. A rejected request answers `429 rate_limit_error` (`code: rate_limit_exceeded`) with a `retry-after` header. |
| `OPENCODE_RATE_LIMIT_RPM` | integer ≥ 0 | `0` | Sustained requests per minute allowed per authenticated API key; `0` disables this limiter. `/admin/*` uses its own separate bucket, and `/metrics` is charged to the per-key bucket like any other route. Failed authentication is throttled by a bucket that is always active (at least 60 failed attempts per minute per client address) plus a much higher global ceiling over all addresses, independently of this variable. | Bounds how many paid upstream turns one key can trigger. A rejected request answers `429 rate_limit_error` (`code: rate_limit_exceeded`) with a `retry-after` header. |
| `OPENCODE_RATE_LIMIT_BURST` | integer ≥ 0 | `0` | Token-bucket capacity per API key; `0` derives `max(1, ceil(rpm / 6))`. Ignored when `OPENCODE_RATE_LIMIT_RPM=0`. | A large burst allows that many concurrent turns per key before throttling starts. |

## Authentication
Expand All @@ -42,10 +42,19 @@ variable. (Discovery and the spawned CLI read the variables listed in
| `OPENCODE_METRICS_TOKEN` | string | *(unset)* | Dedicated scrape credential for `GET /metrics`, compared in constant time before the `OPENCODE_METRICS_PUBLIC` bypass. When set, `/metrics` requires it even if `OPENCODE_METRICS_PUBLIC=true`; a valid general API key is still accepted. | Lets a Prometheus scraper read metrics without handing it a general-purpose key. Prefer it over making the endpoint public. |

Keys are presented as `Authorization: Bearer <key>`, `x-api-key: <key>`,
`Authorization: Basic <base64(key:)>` (key as the username). A bare value with no
scheme (`Authorization: <key>`) is **not** accepted. Query-string keys (`?api_key=`) are deliberately **not** supported because request URLs end up in access logs.
`Authorization: Basic <base64(key:)>` (key as the username, empty password). A
bare value with no scheme (`Authorization: <key>`) is **not** accepted, and
neither is a Basic value that carries a password or omits the colon. Query-string
keys (`?api_key=`) are deliberately **not** supported because request URLs end up
in access logs.
Failed authentication is throttled per client address (at least 60 attempts per
minute) and logged at `warn` without the presented value.
minute) and by a much higher global ceiling over all addresses, and logged at
`warn` without the presented value. Because the per-address bucket is keyed on
`request.ip`, a deployment behind a reverse proxy with the default
`OPENCODE_TRUST_PROXY=false` resolves every caller to the proxy address: set
`OPENCODE_TRUST_PROXY` to a hop count or a CIDR list (see "HTTP server") so the
bucket is per caller rather than shared, and so the global ceiling is not what
answers `429` for legitimate clients.
`GET /`, `GET /health`, `GET /ready` and `GET /healthz` are always public.

`pnpm setup` writes `.env` (keeping `sk-dummy-123`); `pnpm setup -- --random` writes
Expand Down Expand Up @@ -112,24 +121,30 @@ section "Vision and media input".

| Variable | Type | Default | Description | Security implication |
| --- | --- | --- | --- | --- |
| `OPENCODE_REASONING_DEFAULT` | `off` \| `on-request` \| `always` | `on-request` | Server-wide policy for thinking effort. Unrecognised values fall back to `on-request`. | `always` selects a thinking variant even when the caller did not ask, raising cost and latency. |
| `OPENCODE_REASONING_DEFAULT` | `off` \| `on-request` \| `always` | `on-request` | Server-wide policy for thinking effort. Unrecognised values fall back to `on-request` and log a warning naming the variable. | `always` selects a thinking variant even when the caller did not ask, raising cost and latency. |
| `OPENCODE_TOOL_BRIDGE_DENY_NATIVE_TOOLS` | boolean | `true` | When a request declares client tools, add `deny` permission rules for OpenCode's built-in actions (`bash`, `webfetch`, `websearch`, `edit`, `write`, `patch`, `task`, `skill`) so the model emits a bridged tool call instead of running its own tools. | **Keep `true`.** Setting it to `false` lets a request that declares any tool also drive the agent's shell, web and file tools. The deny rules are merged on top of `OPENCODE_AGENT_PERMISSIONS` for that session only. |
| `OPENCODE_EXPOSE_NATIVE_TOOLS` | boolean | `false` | Stream native OpenCode tool activity as SSE events (see `OPENCODE_NATIVE_TOOL_EVENT`). | Native tool payloads can reveal file paths and command input/output from the agent's workspace. |
| `OPENCODE_NATIVE_TOOL_EVENT` | string | `opencode.tool_call` | SSE event name used for native tool activity. | — |
| `OPENCODE_REASONING_FIELD` | `reasoning_content` \| `both` | `reasoning_content` | `POST /v1/chat/completions` only: when `both`, the adapter emits an extra `reasoning` alias next to `reasoning_content` on messages and deltas. Read into `Config.reasoningField`. | — |
| `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. | `debug`/`trace` add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged. |
| `OPENCODE_LOG_LEVEL` | string | `info` | Pino level: `fatal`, `error`, `warn`, `info`, `debug`, `trace`. Unrecognised values fall back to `info` and log a warning naming the variable. | `debug`/`trace` add upstream request metadata, connection diagnostics and fragments of malformed upstream frames; no prompt text or credential is ever logged. |
| `OPENCODE_LOG_PRETTY` | boolean | `true` when stdout is a TTY | Pretty-print logs instead of JSON lines. | Needs `pino-pretty`, which is a dev dependency; without it the gateway falls back to JSON instead of failing. |
| `OPENCODE_METRICS_ENABLED` | boolean | `true` | Enable Prometheus collection; when false, `GET /metrics` answers `404`. | — |
| `OPENCODE_INSTANCE_ID` | string | `opencode-api-<pid>` | Identifier for this gateway instance. Also the fingerprint of the persisted session cache (`OPENCODE_SESSION_PERSIST`). | Changing it invalidates the persisted session cache. |

Boolean values accept `1/true/yes/on/enabled` and `0/false/no/off/disabled`
(case-insensitive). Any other value falls back to the default.
(case-insensitive). Any other value is unrecognised: the default is kept and a
warning naming the variable is logged.

Integer values must be a whole number: the entire value is parsed, so
`OPENCODE_REQUEST_TIMEOUT_MS=10m` is **not** read as 10 seconds — it is treated as
unrecognised, the default is kept and a warning naming the variable is logged.
Out-of-range integers are clamped to the documented bounds.

`OPENCODE_REASONING_DEFAULT` and `OPENCODE_LOG_LEVEL` are unrecognised in the same
way: the default (`on-request`, `info`) is kept and a warning naming the variable
is logged. The warning never echoes the value, because an operator can paste a
secret into the wrong variable.

## Environment variables read by other libraries

`dotenv` loads `.env` from the project root and then the working directory. The
Expand Down Expand Up @@ -161,7 +176,8 @@ logged when the published key is configured explicitly — including the
`.env.example` default that `pnpm setup` copies — because in that case the port is
just as unprotected.
Every variable is otherwise clamped to its documented bounds, and an unrecognised
boolean/integer falls back to the default.
boolean, integer, reasoning default or log level falls back to the default with a
warning naming the variable.

## Recommended hardening for a reachable deployment

Expand Down
2 changes: 1 addition & 1 deletion docs/VERIFICATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ FAIL POST /v1/chat/completions (non-streaming)
| Bad body, chat / responses | `400 invalid_request_error` with `param` | OK |
| Bad body, `/v1/messages` | `400 {"type":"error","error":{"type":"invalid_request_error",...}}` | OK |
| `POST /v1/messages` without key | `401` **Anthropic** shape | OK |
| Auth transports | Bearer, `x-api-key`, `Basic base64(key:)`, `?api_key=` all `200` | OK |
| Auth transports | Bearer, `x-api-key`, `Basic base64(key:)` all `200`; a query-string key is not a transport and answers `401` | OK |
| `POST /v1/chat/completions` (real model) | `429` + `retry-after: 57508`, `code":"provider.free-limit"` | OK (expected quota) |
| `POST /v1/messages` (real model) | `429` + `retry-after: 57507` | OK (expected quota) |
| `POST /v1/responses` (real model) | `429` + `retry-after: 57507` | OK (expected quota) |
Expand Down
52 changes: 51 additions & 1 deletion src/adapter/anthropic/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,58 @@ export interface ToInternalOptions {
budget?: MediaBudget;
}

/**
* Optional top-level fields for which an explicit `null` means "unset".
*
* Anthropic SDKs and the proxies in front of them serialise an untouched option
* as `null`, and the real API accepts that; zod rejects `null` for a plain
* `.optional()`, so without this the same request that `/v1/chat/completions`
* accepts (the OpenAI surfaces strip these too, see `normaliseNullFields` in
* `src/adapter/openai/chat.ts`) was answered `400 invalid_request` here.
* Required fields (`model`, `messages`) and per-message `content` are
* deliberately absent: a `null` there is a genuine defect.
*/
const NULL_MEANS_UNSET_FIELDS: ReadonlySet<string> = new Set([
"max_tokens",
"system",
"stream",
"temperature",
"top_p",
"top_k",
"stop_sequences",
"metadata",
"tools",
"tool_choice",
"thinking",
"reasoning_effort",
"service_tier",
"container",
"mcp_servers",
]);

/**
* Drop explicit `null` values for the optional top-level request fields.
*
* Every other key (including unknown ones) is passed through untouched, so
* nothing else about validation changes. The original object is returned when
* there is nothing to strip.
*/
export function normaliseNullOptionals(body: unknown): unknown {
if (typeof body !== "object" || body === null || Array.isArray(body)) return body;
let changed = false;
const normalised: Record<string, unknown> = {};
for (const [key, value] of Object.entries(body)) {
if (value === null && NULL_MEANS_UNSET_FIELDS.has(key)) {
changed = true;
continue;
}
normalised[key] = value;
}
return changed ? normalised : body;
}

function parseOrThrow<S extends z.ZodType>(schema: S, body: unknown, label: string): z.output<S> {
const parsed = schema.safeParse(body);
const parsed = schema.safeParse(normaliseNullOptionals(body));
if (parsed.success) return parsed.data;
const issue = parsed.error.issues[0];
const path = issue ? issue.path.map((segment) => String(segment)).join(".") : "";
Expand Down
Loading
Loading