Repository navigation
fix: harden request handling, wire streams and session hashing - #21
Merged
Merged
Conversation
Arm the body-receipt deadline in the earliest `onRequest` hook. Fastify runs `preParsing` only while no earlier hook ended the request, and both the authenticator and the rate limiter reject from `onRequest`, so the deadline was never installed for a rejected request: an unauthenticated caller could dribble a body forever and hold a socket for free. The deadline now survives the response `close` while the body is still arriving. Reject an `OPENCODE_SERVER_URL` that embeds credentials at startup. Node refuses a request whose URL carries userinfo, so such a deployment could never reach its upstream, and the password was echoed by `/admin/config` and `/admin/status` and every completion failure message. `OPENCODE_SERVER_PASSWORD` is the documented way to authenticate. Warn when `OPENCODE_METRICS_PUBLIC` publishes `/metrics` anonymously on a host reachable from the network, matching the fail-loud note the private-media switch already gets. Each fix has a regression test that fails without it.
`/v1/responses` emitted the closing frames of an item in block order (reasoning, then message) while `output_index` is fixed when the item is announced. A turn that streams text before its reasoning announces the message at index 0 and the reasoning item at index 1, so the `response.output_item.done` frames arrived as 1,1,1,0,0,0 while the terminal `response.output` was sorted by index: a client assembling `output[]` from the `.done` frames got the reverse of one reading the result object. Each item now records its closing frames and they are emitted in ascending index order. `/v1/messages` returned as soon as it had written the terminal `error` frame for a failed turn, before flushing the withheld text and closing the blocks the turn had opened. An SDK that assembles the message on `content_block_stop` never finished it. The block is closed before the error event; no `message_delta`/`message_stop` is added, which `docs/API.md` forbids on that path.
`toUsage()` computed `totalTokens` as input + output + reasoning, while every surface derives its wire `total_tokens` (and Anthropic `output_tokens`) as prompt + completion with the thinking tokens already inside completion, which is what `docs/API.md` documents. The field is internal and unread today, so nothing on the wire changes; it is the value every future surface would read, and it was arithmetically inconsistent with the payloads built from the same event.
`acquire()` joined and SHA-256'd one candidate's delivered prefix at a time, so a conversation under the full `MAX_CANDIDATES_PER_ROOT` records was re-serialised once per candidate - with base64 media, megabytes of avoidable copying per turn on the request path. The candidates' prefixes are nested, so one ascending pass now feeds a single hash stream and takes `Hash#copy().digest()` per length. The byte stream is unchanged, so persisted `prefixHash` values stay compatible. `StderrTail.push()` clamped the whole chunk to 8 KiB before splitting, which discarded every complete line a burst carried; splitting now walks back from the last terminator, so `/admin/status` keeps the last 50 lines it documents. The log-file redaction boundary scan is bounded to the suffix that can still grow into a marker, and the marker patterns are compiled once instead of per chunk, matching the documented promise that a chatty long-lived child costs no per-chunk full scan. An `UpstreamProcess` is dropped from the process-exit registry once it owns no child and has no start in flight; the registry is re-armed on the next spawn, so a host that builds and disposes gateways with the non-terminal `stop()` no longer retains each one.
`src/upstream/discovery.ts` resolves the `opencode` executable from PATH and the well-known install directories, parses `service.json` and checks a PID. Every other test injects both as seams, so the Windows `%APPDATA%`/`%LOCALAPPDATA%` branches and the descriptor parsing could regress with the suite green. The new cases drive the real functions against a temporary PATH and `XDG_STATE_HOME`/`XDG_CONFIG_HOME`. The integration file no longer reports a passing test that asserts nothing (`expect(true).toBe(true)`): without `OPENCODE_API_URL` and `OPENCODE_API_KEY` it reports its cases as skipped, which is what `pnpm test:all` already refuses to accept as a real run.
`docs/API.md` labelled five `/admin/*` routes "admin key" although the
tier is opt-in: with `OPENCODE_ADMIN_API_KEYS` unset any accepted key
reaches them, which the same document's introduction, the configuration
reference and `src/auth.ts` all say.
The README endpoint table was missing `GET /v1/models/*`, the only route
that can address a `provider/model` id, and its `{id}` row promised that
form. It also omitted `pnpm start` and three source modules plus four of
the five scripts from the project layout.
`CONTRIBUTING.md` and `AGENTS.md` told contributors to run the checks CI
runs but left out `pnpm smoke:dist` and `pnpm audit --prod`, both steps
of the required `Verify` job.
`docs/CONFIGURATION.md` called its startup-validation list exhaustive
while omitting the `OPENCODE_ADMIN_API_KEYS` refusal and the credential
check added for `OPENCODE_SERVER_URL`.
`docs/ARCHITECTURE.md` now lists the third model route it owns, the
frozen `MessageRole` type and the two `mime.ts` exports it was missing,
and documents that `Usage.totalTokens` counts reasoning inside output.
`.dockerignore` covers the runtime and scratch paths `.gitignore` has.
The previous commit asserted that reasoning is a subset of `Usage.outputTokens` and dropped it from `totalTokens`. That is the wire shape, not the internal one: upstream `tokens.output` excludes the thinking tokens, and every surface builds its own completion as `output + reasoning` (`src/adapter/openai/chat.ts`, `src/adapter/openai/responses.ts`, `src/adapter/anthropic/messages.ts`), while its prompt folds in the cache buckets. `totalTokens` is back to `input + output + reasoning`, now with a JSDoc, an architecture note and `test/usage.test.ts` stating why it is not any surface's `total_tokens`.
Keeping the deadline armed for a rejected request's dribble left one residual path: Node dumps the unread remainder of a rejected request and reuses the socket, so by the time the timer fired the connection could be serving a healthy `stream: true` response, which the timer then destroyed. The timer now repeats the completeness check before touching the socket, which keeps the dribble bound and spares the connection.
dinhdev666
force-pushed
the
perf/harden-and-optimize
branch
from
December 5, 2026 08:23
0c1fb87 to
c7367ab
Compare
Three defects in the log-file redaction path, all around the boundary between two chunks: `pending.slice(0, boundary - hold)` treats a negative end as an offset from the end of the string, so a marker starting before the boundary was still written *past* it; the cut is clamped instead, which is what the comment already claimed. The bounded scan window could fall inside a long run of whitespace between `server password` and its value, where the `marker\s+$` alternative no longer sees the marker and the hold shrinks to zero. The window is now exactly the suffix that can affect the decision: the trailing whitespace run plus the longest marker. `StderrTail.push()` counted empty segments against its walk budget while `#append` drops them, so a burst ending in blank lines could exhaust the walk before reaching a line that was complete in the same chunk.
The endpoint table and section 8 still described `{id}` as accepting the
unencoded `provider/model` form, which is served by the separate
`GET /v1/models/*` route, and neither listed that route.
dinhdev666
force-pushed
the
perf/harden-and-optimize
branch
from
December 5, 2026 08:30
c7367ab to
00255b5
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.
Closes the findings of a four-angle audit (security, upstream/performance,
wire adapters, docs/CI consistency) on top of
6bc7ab8.Security
OPENCODE_BODY_TIMEOUT_MSwas armed inpreParsing, which Fastify neverreaches for a request an
onRequesthook rejected, so an unauthenticatedcaller could dribble a body and hold a socket for free.
OPENCODE_SERVER_URLmay no longer embed credentials: Node refuses a requestwhose URL carries userinfo, so it could never work, and the password reached
/admin/config,/admin/statusand every completion failure message.OPENCODE_METRICS_PUBLICon a network-reachable host with no token now warnsat startup, like the private-media switch already did.
Wire correctness
/v1/responsesclosed its items in block order rather thanoutput_indexorder, so a text-then-reasoning turn emitted the
response.output_item.doneframes as
1,1,1,0,0,0whileresponse.completed.response.outputwas sortedby index.
/v1/messagesreturned before closing the content blocks a failed turn hadopened.
Usage.totalTokensno longer double-counts reasoning tokens.Performance
of joining and hashing the conversation once per cached candidate (measured
~4.8 ms -> ~1.3 ms per turn over four candidates, and a 20 MiB transcript
copied once instead of four times).
StderrTailkeeps the complete lines of a burst instead of clamping the chunkbefore splitting, and the log-file redaction boundary scan is bounded and its
patterns are compiled once.
UpstreamProcessleaves the process-exit registry once it owns no child.Docs and tests
docs/API.md,README.md,CONTRIBUTING.md,AGENTS.md,docs/CONFIGURATION.md,docs/ARCHITECTURE.mdand.dockerignoreare back insync with the code.
test/discovery.test.tscovers the CLI/service.jsondiscovery that had notest at all; the integration file no longer reports a passing test that
asserts nothing.
Every fix has a regression test that fails without it.
Verification