Skip to content

fix: harden request handling, wire streams and session hashing - #21

Merged
dinhdev666 merged 10 commits into
mainfrom
perf/harden-and-optimize
Dec 5, 2026
Merged

dinhdev666 merged 10 commits into
mainfrom
perf/harden-and-optimize

Conversation

@dinhdev666

Copy link
Copy Markdown
Owner

Closes the findings of a four-angle audit (security, upstream/performance,
wire adapters, docs/CI consistency) on top of 6bc7ab8.

Security

  • OPENCODE_BODY_TIMEOUT_MS was armed in preParsing, which Fastify never
    reaches for a request an onRequest hook rejected, so an unauthenticated
    caller could dribble a body and hold a socket for free.
  • OPENCODE_SERVER_URL may no longer embed credentials: Node refuses a request
    whose URL carries userinfo, so it could never work, and the password reached
    /admin/config, /admin/status and every completion failure message.
  • OPENCODE_METRICS_PUBLIC on a network-reachable host with no token now warns
    at startup, like the private-media switch already did.

Wire correctness

  • /v1/responses closed its items in block order rather than output_index
    order, so a text-then-reasoning turn emitted the response.output_item.done
    frames as 1,1,1,0,0,0 while response.completed.response.output was sorted
    by index.
  • /v1/messages returned before closing the content blocks a failed turn had
    opened.
  • Usage.totalTokens no longer double-counts reasoning tokens.

Performance

  • Sticky-session prefix verification hashes one ascending pass per turn instead
    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).
  • StderrTail keeps the complete lines of a burst instead of clamping the chunk
    before splitting, and the log-file redaction boundary scan is bounded and its
    patterns are compiled once.
  • An UpstreamProcess leaves 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.md and .dockerignore are back in
    sync with the code.
  • test/discovery.test.ts covers the CLI/service.json discovery that had no
    test 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

pnpm typecheck   # clean
pnpm build       # clean, 78 files in dist/
pnpm test        # 32 files, 789 passed, 2 skipped
pnpm smoke:dist  # /health answered, clean SIGTERM shutdown
pnpm audit --prod # no known vulnerabilities

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
dinhdev666 force-pushed the perf/harden-and-optimize branch from 0c1fb87 to c7367ab Compare December 5, 2026 08:23
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
dinhdev666 force-pushed the perf/harden-and-optimize branch from c7367ab to 00255b5 Compare December 5, 2026 08:30
@dinhdev666
dinhdev666 merged commit 1f09d7b into main Dec 5, 2026
5 checks passed
@dinhdev666
dinhdev666 deleted the perf/harden-and-optimize branch December 5, 2026 08:33
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