Repository navigation
fix: harden the request path, streaming and completion metrics - #8
Merged
Merged
Conversation
Authentication and the rate limiter were `preHandler` hooks, and Fastify parses the body between `preParsing` and `preHandler`, so an anonymous caller made the gateway buffer and JSON-parse up to OPENCODE_MAX_BODY_BYTES (64 MiB) per connection with no credential. Both hooks now run `onRequest`, after the CORS hooks. Credential-less callers are bucketed by `request.ip` (proxy-aware when `trustProxy` is on) instead of sharing one anonymous bucket, and the bucket map is capped so a rotating address cannot grow it without bound. The public-path check canonicalises trailing slashes and repeated separators, so `/metrics/` can no longer fingerprint `/metrics`. The public `GET /` index now lists every registered route, with a test asserting the two sets stay equal.
`AbortSignal.timeout()` cannot be disarmed and undici keeps the signal attached to the response body, so the connect-phase watchdog aborted every healthy `/api/event` stream after 45 s. Each reconnect marked a stream gap for every in-flight turn, which then failed with `503 event_stream_lost` when its terminal event did not arrive within the grace window. The connect deadline is now a cancellable timer that is cleared once the response head arrives; reads stay bounded by the same watchdog. The frame-assembly buffer was also unbounded and rescanned from offset zero on every chunk, so a stream without a blank line grew without limit and cost quadratic CPU. It is capped at 1 MiB: an oversized partial frame is dropped and counted instead of retained. Finally, `stop()` retires the running loop with a generation stamp so a racing `start()` cannot leave two consumers on the same response body.
`prepare()` ran outside the handler, so model resolution, modality validation, session creation and `upstream_unavailable` failures never reached `completions_total`, although the docs promise an outcome for every exit. Pre-flight failures are now counted once, with the resolved model or `unknown` when resolution itself failed. The `error_code` label was also filled verbatim from upstream payloads (`record.type` / `_tag`), which prom-client never evicts: every distinct tag became a permanent time series. The label is now a closed allow-list with `other` as the fallback. When a turn fails before it settles, its sticky record is released; for a session created for that turn no record exists yet, so the eviction hook never fired and the upstream session leaked for the life of the server. The same `finally` now deletes it, best effort, on every failed fresh turn.
Only completed stderr lines were capped, so an unterminated line (a child writing binary garbage, or simply never emitting a newline) grew `#partial` without bound and made every later chunk cost O(partial). The retained tail is now clamped to 8 KiB; an over-long line is diagnostic only.
A forced refresh (`GET /v1/models?refresh=1`, `POST /admin/models/refresh`) or a TTL expiry that answered an empty model list cleared the previously good catalogue. Every later request then failed with `model_not_found` and paid the cold-start retry on each call until a non-empty answer happened to load. The previous catalogue is kept (with a refreshed timestamp) while the real, empty answer is still returned to the caller.
A turn hashes the conversation three times (acquire, commit and the root message in `deriveKey`), re-serialising every base64 media payload each time: about 40 ms of avoidable CPU and tens of MiB of transient strings per attachment-heavy turn. Per-message JSON is memoised by object identity and joined into the array form, which is byte-identical to `JSON.stringify(messages)` so persisted prefix hashes stay valid. `reusedCount` is incremented on commit as well: it was read from the record and never written, so `/admin/sessions` always reported 0.
A provider that delivers its answer only in `session.text.ended` produced an empty 200 SSE response on `/v1/chat/completions`, `/v1/completions` and `/v1/messages`, while the buffered route for the same request carried the answer. Those three streamed paths now adopt a consolidated `text_end` / `reasoning_end` only when it is longer than what the deltas already produced, which is the documented rule `/v1/responses` and `collectCompletion()` already applied. `/v1/responses` now fixes an item's `output_index` when the item is announced and reuses it everywhere, so a text-then-reasoning turn no longer announces two items at index 0 or ends with an `output[]` that contradicts the stream. A step-level `reasoning_end` snapshot is adopted only when longer, and the reasoning summary is closed once per turn instead of once per step. The Anthropic stream kept the `stop_sequences` filter between it and the tool calls, so a matched sequence swallowed a call the buffered route returns; every call is reported again. Its stop-sequence filter was O(n²) in the length of the retained tail (64 KiB took about 5 s and blocked the event loop); it now uses the O(1) hold rule the chat adapter uses. The tool-envelope fence parsing is linear for the same reason.
`GET /` and `docs/API.md` omitted five registered routes (`/healthz`, the model refresh, the two session routes and the upstream restart). The metrics reference gave `upstream_request_duration_seconds` an `outcome` label it does not have, README listed ten of the thirteen exported series, and `/metrics` was missing from the rate-limit exemptions. The verification addendum had stale counts and line references. The docs-consistency test now also compares the documented `GET /` index against the routes `src/` registers, and every metric series against both documents, so the next addition cannot drift unnoticed.
The docker job only built the image and validated the compose file, so `pnpm prune --prod`, the copied file set and the HEALTHCHECK were never exercised. It now starts the image with `OPENCODE_AUTOSTART=false` and a test key, polls `/health` on a Docker-assigned port and fails when the container exits. Dependabot gains the `docker` ecosystem so a base-image security release arrives as a pull request, and `.dockerignore` excludes `.env` so a real key file never enters the build context.
`shuttingDown` is set before `performShutdown()` is awaited and later signals are ignored, so a rejecting shutdown left the process alive with the HTTP server closed and no exit code for the supervisor. The rejection is logged and the process exits with status 1.
dinhdev666
force-pushed
the
fix/security-perf-hardening
branch
from
December 3, 2026 06:33
2dc29e9 to
44b5d39
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changes
A hardening pass over the request path, the upstream event stream, the
completion metrics and the streamed adapters. Ten commits, one per
concern; the per-commit bodies explain each one.
Security
onRequest, so an anonymouscaller can no longer make the gateway buffer and JSON-parse up to
64 MiB per connection before being rejected;
bucket map) instead of sharing one anonymous bucket;
GET /index nowlists every registered route.
Upstream
healthy
/api/eventstream is no longer aborted every 45 s;stop()/start()race canno longer run two event loops;
completions_totalcounts pre-flight failures and itserror_codelabel is closed; a failed first turn deletes the session it created;
reusedCountis incremented, andeach message is serialised once per turn.
Streaming
/v1/chat/completions,/v1/completionsand/v1/messagesadopt aconsolidated
text_endlike the other paths already did (they used toanswer an empty 200 when the provider sent no deltas);
/v1/responsesfixesoutput_indexat announcement time and adopts astep-level
reasoning_endonly when it is longer;/v1/messageskeeps tool calls the buffered route returns after astop-sequence match, and its stop-sequence scan is O(1) instead of
O(n²) (64 KiB went from ~5 s to under 2 ms).
Docs, CI, Docker
docs-consistency test extended to enforce both;
/health;.dockerignoreexcludes.env.Verification
pnpm typecheckpnpm buildpnpm testpnpm smoke:distdist/index.js answered /health with version 1.0.0)docker build+docker run+GET /healthdocker compose config --quietpnpm exec commitlint --from main --to HEAD