Skip to content

feat: harden the gateway and complete the surface contracts - #7

Merged
dinhdev666 merged 12 commits into
mainfrom
feat/gateway-hardening-and-observability
Dec 3, 2026
Merged

dinhdev666 merged 12 commits into
mainfrom
feat/gateway-hardening-and-observability

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

Implements the improvement round recorded before this branch: upstream
lifecycle and event-stream hardening, the OpenAI and Anthropic surface
contract fixes, operational security (per-key rate limiting, a metrics
scrape token, private media blocked by default), the Docker/Windows CI
jobs with pinned actions, and the missing parity, metrics, admin and
docs-consistency tests.

Verification run on this branch:

pnpm typecheck   clean
pnpm build       clean
pnpm test        24 files, 493 passed | 4 skipped
pnpm smoke:dist  answered /health with version 1.0.0
docker build     succeeded (node:22-bookworm-slim image)

BREAKING CHANGE: OPENCODE_ALLOW_PRIVATE_MEDIA_URLS now defaults to false,
so remote media on loopback, private, link-local and metadata addresses is
rejected unless the variable is set to true explicitly. Verified live: no.

Refs: none.

A vanished sticky session could not be replayed: fromUpstreamError()
collapsed every upstream 4xx, including 404, into a caller-fault 400,
so isStaleSession() was dead code and a dead ses_* id failed the whole
conversation until its TTL expired. Preserve 404 as not_found_error,
classify the replay on either field, and mirror the rate-limit and 404
handling in the event-path classifier.

Four operational gaps found while auditing the module are closed too:
the /api/event connect phase had no timeout, so an upstream that
accepted the socket and never wrote a response head parked the hub for
undici's header timeout and failed every concurrent turn with 503; a
failed start was not remembered, so every incoming request re-spawned
the CLI (a bounded exponential backoff now fails fast); the child's
stdout and stderr were accumulated and rescanned for the whole process
lifetime, which was unbounded memory and quadratic CPU; and stop()
left the event_stream_connected gauge at 1 while a response head reset
the reconnect delay, so a flapping stream was polled four times a
second.

The caller's abort signal now reaches createSession() and prompt(),
the request gauges no longer flatten and sort the whole session cache,
a consolidated text_end is adopted when it is longer than the deltas,
and completions_total records an outcome for every failure through a
bounded error_code label. The process exit hook is installed once per
process instead of once per instance.
The reasoning item was never announced with
response.output_item.added, yet the message item was opened at
output_index 1, so a client building output[] from the stream saw a
hole at index 0 and a late .done for it. Announce the reasoning item
first, at index 0, in both the delta and the consolidated branch.

A filtered turn was reported as completed, a length limit was the only
incomplete reason, created_at was recomputed on every frame,
instructions was always null even when the caller sent it, a failed
stream fabricated all-zero usage, and text that arrived only in the
consolidated text_end event was in output_text but missing from
output.

Report content_filter as incomplete with the documented
incomplete_details.reason, capture created_at once per response, echo
instructions, use null usage when no usage event arrived, and open the
message item for text_end-only turns. Text accumulation is now a
string list joined once at finalise.
stop was accepted and then ignored, so the delimiter stayed in the
answer and finish_reason stayed stop; it is now a text-truncation
filter shared by both paths, exactly like the Anthropic surface,
without interrupting the upstream turn. Requests from different
messages no longer download their media one message at a time: the
adapters build every media source first and resolve them through one
request-wide pool.

Fields that would change the shape of the response and cannot be
emulated were accepted and silently dropped. logprobs and
top_logprobs, non-text modalities, audio, prediction, store: true,
web_search_options, the legacy functions and function_call pair,
previous_response_id, non-empty include, best_of and suffix now answer
400 unsupported_parameter naming the field. image_url.detail accepts
only auto. A tool_choice that names a function the request never
declared is rejected instead of being answered with prose.

The generation knobs OpenCode's agent loop owns stay accepted for
client compatibility, but every response names them in
x_opencode.unapplied so a caller can detect that they were not
applied. The tool-call envelope filter no longer rescans the whole
accumulated body per delta.
max_tokens is required by the Anthropic schema but accepted zero and
negative values, a turn the upstream reported as failed was rendered
as a successful end_turn with partial text, a streamed message_start
advertised zero usage while the docs presented it as the usage
carrier, thinking.effort was advertised as tolerated but stripped by
the schema, and disable_parallel_tool_use was ignored even though the
bridge supports capping the turn at one call.

Require an integer of at least 1, answer a failed turn with 502
api_error when buffered and a terminal error event when streamed, mark
a cancelled turn with x_opencode.interrupted, accept thinking.effort,
and honour disable_parallel_tool_use. count_tokens now charges inline
media with a documented bytes-per-token constant instead of a fixed
placeholder, so a large image is no longer counted as five tokens.
One authenticated caller could open unlimited concurrent sockets and
drive unlimited paid upstream turns: nothing limited request rate, and
the server disabled the request timeout globally. Add an in-process
token bucket keyed by a hash of the authenticated key (never the raw
key), with a separate bucket for /admin/*, wired as a preHandler
beside requireApiKey; OPENCODE_RATE_LIMIT_RPM=0 keeps the previous
behaviour and a rejection answers 429 with retry-after. Buffered
routes get a bounded socket timeout again while streaming routes stay
unbounded.

OPENCODE_METRICS_TOKEN lets a scraper read /metrics with a dedicated
credential, compared in constant time before the metricsPublic bypass,
so the endpoint no longer has to be anonymous to be scraped. The
logger redaction list now covers every secret field the code actually
builds, including upstreamPassword and nested authorization headers.
The SseWriter reports backpressure instead of discarding it: drain()
resolves when the socket catches up or after a bounded wait, and
closedSignal aborts when the connection dies, so a dead reader stops
the producer on every surface.

BREAKING CHANGE: OPENCODE_ALLOW_PRIVATE_MEDIA_URLS now defaults to
false. Remote media on loopback, private, link-local and metadata
addresses is rejected unless the variable is set to true explicitly;
enabling it while HOST is not a loopback address logs a startup error.
The remote download asked for accept-encoding: identity but never
inspected the response, and the byte caps bound the bytes as received,
so a compressed body under the cap was inlined and labelled as media
of the declared type. Reject any non-identity content-encoding with
attachment_download_failed instead.

On Windows O_NOFOLLOW collapses to 0, so the realpath-then-open
sequence had no final-component guarantee on the platform this project
is developed on. The final component is now lstat-checked for a
symlink or junction before the open, and the opened handle's dev and
ino are compared with the pre-open lstat, refusing the read on any
mismatch.

isPrivateHost() also normalises the address itself now: any IPv6
spelling is expanded before classification, so it is correct for
non-canonical input instead of relying on new URL() having
canonicalised the hostname.
GET /metrics had no HTTP-level test at all, including the
metricsPublic bypass and the new scrape token, and five /admin/*
routes were untested at the HTTP layer. Add both, plus a table-driven
suite that runs the same scripted turn through stream: false and
stream: true on all four completion surfaces and compares text, ids,
finish reason, usage and the Responses output items, so a change that
only handles one path fails immediately.

The docs-consistency test parses the environment variables out of
src/config.ts and asserts that .env.example, docs/CONFIGURATION.md and
the README configuration summary agree with the code in both
directions, which is what keeps three hand-maintained tables honest.
The README documents a Docker deployment but no job built the image,
so a broken Dockerfile could merge unnoticed, and the suite has
Windows-only paths the Ubuntu matrix never runs. Add both jobs as
additive entries: the three required check names and the 20.x and 22.x
matrix entries are unchanged.

Pin every action to the commit SHA of its release tag with the tag in
a trailing comment, since a moved tag would silently change what runs
in a workflow that holds a repository token, add a weekly Dependabot
config for npm and github-actions, and keep pnpm audit --prod as the
hard gate while reporting the dev toolchain advisories without
blocking.
pnpm build now removes dist/ first, so a deleted or renamed source
file cannot leave a stale module behind for smoke:dist to boot. The
clean step lives in scripts/ because a Docker build stage runs it.

pnpm test:all used to equal pnpm test: the integration suite skips
itself when no gateway is configured, so the script silently degraded
to a unit-only run. It now refuses to start, naming the two variables,
instead of pretending the integration tests ran.
noUnusedLocals, noUnusedParameters and verbatimModuleSyntax now run in
pnpm typecheck; the five dead declarations they found were removed,
and EventHub keeps its constructor arity with an intentionally unused
config parameter.

exactOptionalPropertyTypes stays off: enabling it produces 55 errors
that span the frozen internal contract, which is a separate change of
its own.
Bring every reference in line with the code in the same change that
altered it: the new rate-limit and metrics-token variables and the
private-media default in CONFIGURATION.md and the README summary, the
rejected-versus-recorded field policy and x_opencode.unapplied in
API.md, the Anthropic schema and status changes, count_tokens media
accounting, the metrics table with the completion error_code
dimension, and the operational-route behaviour that changed.

ARCHITECTURE.md records the new internal facts: 404 preservation for
session replay, the start backoff window and connect-phase bound, the
one-handle Windows file check, the media content-encoding rule, the
drain and closedSignal contract, the adapter helpers that the
Responses surface shares with chat, and the outcome metrics.
VERIFICATION.md gains a dated addendum so its historical findings are
not read as the current state, and CONTRIBUTING.md documents what pnpm
test:all now refuses to do.
The local-file containment check canonicalised the candidate with
realpath but compared it against lexically resolved roots. On Windows
a root reached through an 8.3 short name or a junction - exactly what
os.tmpdir() returns on a CI runner - resolves to a different string
than a file below it, so every legitimate local attachment was
rejected with attachment_path_forbidden. Canonicalise each root the
same way as the candidate, keeping the lexical form when a root does
not exist yet, and pin it with a test that resolves a file through a
directory link.
@dinhdev666
dinhdev666 merged commit 87d10db into main Dec 3, 2026
5 checks passed
@dinhdev666
dinhdev666 deleted the feat/gateway-hardening-and-observability branch December 3, 2026 05:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant