Skip to content

fix: prevent server crash on unauthenticated requests (ERR_HTTP_HEADERS_SENT) - #47

Open
XciD wants to merge 3 commits into
mainfrom
fix/headers-sent-crash
Open

fix: prevent server crash on unauthenticated requests (ERR_HTTP_HEADERS_SENT)#47
XciD wants to merge 3 commits into
mainfrom
fix/headers-sent-crash

Conversation

@XciD

@XciD XciD commented Aug 1, 2026

Copy link
Copy Markdown
Member

Problem

A single POST /v1/responses without an Authorization header crashes the whole server. In production (responses-js-prod), this shows up as recurring pod restarts with:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at postCreateResponse (...)

The chain: innerRunStream answered the missing-key case itself with res.status(401).json(...) and then returned normally. The parent generator runCreateResponseStream still yielded a response.completed event, so postCreateResponse called res.json() a second time, which throws ERR_HTTP_HEADERS_SENT. Since Express 4 does not catch errors from async handlers, the throw becomes an unhandled rejection and kills the Node process. Any unauthenticated probe (scanner, health check, curl without a token) takes the service down.

Fix

  • Check the API key in postCreateResponse before starting the event stream, and pass it down explicitly (runCreateResponseStream / innerRunStream no longer touch res).
  • Wrap the handler body in try/catch: an unexpected error now returns a 500 (or ends the stream if headers were already sent) instead of crashing the process.

Verification

Reproduced the crash on main (one unauthenticated request kills the server), then with the fix:

  • unauthenticated request (stream and non-stream) returns 401, server stays up
  • invalid token returns a well-formed response.failed object
  • added a regression test (unauthenticated request gets a 401 and does not crash the server)
  • pnpm run check and pnpm run lint:check pass

@XciD
XciD requested a review from Wauplin August 1, 2026 08:24
@XciD
XciD marked this pull request as ready for review August 1, 2026 08:28
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