Skip to content

fix(server): ignore websocket messages received after close - #2373

Merged
dinwwwh merged 2 commits into
mainfrom
claude/pensive-brown-s3mw4g
Nov 2, 2026
Merged

dinwwwh merged 2 commits into
mainfrom
claude/pensive-brown-s3mw4g

Conversation

@dinwwwh

@dinwwwh dinwwwh commented Nov 2, 2026

Copy link
Copy Markdown
Member

Problem

With binary Blob frames, WebSocketHandler.upgrade() awaits loadBytes(event.data) before calling .message(). If the client sends a request and closes at once, the close listener runs .close(ws) during that await. When the Blob finishes loading, .message() finds no peer, creates and stores a new ServerPeer, and runs the procedure.

No close event will ever come for that peer, so:

  • its AbortController never fires, and the procedure's signal stays un-aborted;
  • long-running procedures such as subscriptions keep running and keep calling send on the closed socket;
  • the peer and the socket stay reachable for as long as the procedure runs.

The same thing happens when .message() is called by hand after .close().

experimental_CrosswsHandler.close() also awaited peer.close() before removing the peer. While that await was pending, a message could be handed to a peer that was partway through closing.

Fix

  • WebSocketHandler and experimental_CrosswsHandler now store null in the existing peers WeakMap on close(). When .message() sees null, it returns the decoded { matched } result without creating a peer or running a procedure. The map is weak, so the null entry goes away when the socket is garbage-collected.
  • crossws close() now marks the peer closed before awaiting peer.close(), the same order the websocket and message-port adapters already used.

Tests

  • websocket: a Blob message sent through upgrade() that finishes loading after close does not run the procedure or send anything.
  • websocket and crossws: .message() after .close() does not run the procedure or send anything.

All three tests fail without the fix. pnpm vitest run packages/server/src/adapters, pnpm type:check and pnpm lint pass.

Not included

MessagePortHandler uses the same lazy-peer pattern but has no async gap before .message(), so this PR leaves it unchanged. A shared helper for all three adapters would be a good follow-up.


Generated by Claude Code

With binary Blob frames, `upgrade()` awaits `loadBytes` before calling
`.message()`. If the socket closed meanwhile, `.message()` created a new
`ServerPeer` and ran the procedure: no close event would ever abort it,
and the peer entry leaked.

Track closed sockets in a WeakSet so `.message()` ignores messages for a
socket already passed to `.close()`. Apply the same fix to the crossws
handler and delete its peer before awaiting `peer.close()`, matching the
websocket and message-port adapters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7RKXMmm8LBoZPKXUZ5
Replace the separate `closed` WeakSet with a `null` entry in the
existing `peers` WeakMap, so each handler keeps one structure per
socket and `close()` no longer needs a delete-before-close ordering.

Tests: wait on the actual `.message()` call instead of a fixed 50ms
sleep, and let `createWs` capture listeners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7RKXMmm8LBoZPKXUZ5
@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
orpc 7c231da Commit Preview URL

Branch Preview URL
Nov 02 2026, 12:59 AM

@pkg-pr-new

pkg-pr-new Bot commented Nov 2, 2026

Copy link
Copy Markdown
More templates

@orpc/ai-sdk

npm i https://pkg.pr.new/@orpc/ai-sdk@2373

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@2373

@orpc/bun

npm i https://pkg.pr.new/@orpc/bun@2373

@orpc/client

npm i https://pkg.pr.new/@orpc/client@2373

@orpc/cloudflare

npm i https://pkg.pr.new/@orpc/cloudflare@2373

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@2373

@orpc/effect

npm i https://pkg.pr.new/@orpc/effect@2373

@orpc/evlog

npm i https://pkg.pr.new/@orpc/evlog@2373

@orpc/hibernation

npm i https://pkg.pr.new/@orpc/hibernation@2373

@orpc/json-schema

npm i https://pkg.pr.new/@orpc/json-schema@2373

@orpc/experimental-lock

npm i https://pkg.pr.new/@orpc/experimental-lock@2373

@orpc/mcp

npm i https://pkg.pr.new/@orpc/mcp@2373

@orpc/msw

npm i https://pkg.pr.new/@orpc/msw@2373

@orpc/nest

npm i https://pkg.pr.new/@orpc/nest@2373

@orpc/next

npm i https://pkg.pr.new/@orpc/next@2373

@orpc/node

npm i https://pkg.pr.new/@orpc/node@2373

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@2373

@orpc/opentelemetry

npm i https://pkg.pr.new/@orpc/opentelemetry@2373

@orpc/pinia-colada

npm i https://pkg.pr.new/@orpc/pinia-colada@2373

@orpc/pino

npm i https://pkg.pr.new/@orpc/pino@2373

@orpc/publisher

npm i https://pkg.pr.new/@orpc/publisher@2373

@orpc/ratelimit

npm i https://pkg.pr.new/@orpc/ratelimit@2373

@orpc/server

npm i https://pkg.pr.new/@orpc/server@2373

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@2373

@orpc/swr

npm i https://pkg.pr.new/@orpc/swr@2373

@orpc/tanstack-query

npm i https://pkg.pr.new/@orpc/tanstack-query@2373

@orpc/trpc

npm i https://pkg.pr.new/@orpc/trpc@2373

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@2373

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@2373

commit: 7c231da

@codecov

codecov Bot commented Nov 2, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes — the full PR diff (both commits), tracing the message/close race across upgrade(), sequential, ServerPeer, and the two adapters.

  • WebSocket adapter — peers is now WeakMap<WebSocketLike, ServerPeer | null>; close() writes null, and message() returns the decoded { matched } result without creating a peer or running a procedure when it sees null. Decode was hoisted above the peer lookup so the closed branch can return it.
  • crossws adapter — same null-sentinel pattern; close() now marks the peer closed before await peer.close(), matching the websocket/message-port ordering and closing the half-closed-peer window.
  • Tests — message-after-close coverage for both adapters, plus a Blob-frame-after-close test through upgrade().

The core race is closed correctly: the synchronous window from this.peers.get(ws) through await peer.message(...) is intact, so a close can no longer interleave once a live peer has been read, and a Blob that resolves after close hits the null guard. pnpm vitest run on the two adapter test files passes (19 tests).

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@codspeed

codspeed Bot commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 6 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 28 untouched benchmarks
⏩ 2 skipped benchmarks1


Comparing claude/pensive-brown-s3mw4g (7c231da) with main (b922307)

Open in CodSpeed

Footnotes

  1. 2 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@dinwwwh
dinwwwh merged commit 73a9f98 into main Nov 2, 2026
12 checks passed
dinwwwh pushed a commit that referenced this pull request Nov 2, 2026
Resolve conflicts with #2373: the websocket and crossws handlers keep the
shared `PeerRegistry`, and their tests come from main, which covers the
same after-close cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7Qv8vxXaxrrzEYcVnb
dinwwwh pushed a commit that referenced this pull request Nov 3, 2026
`MessagePortHandler.close()` deleted the port from `peers`, so a later
`.message()` created a new `ServerPeer` that was never closed or aborted.
Mirror the WebSocket/crossws fix (#2373): store `null` on close before
awaiting `peer.close()`, and ignore messages for a closed port.

Also correct the PBKDF2 iteration comment in `helpers/encryption.ts`:
OWASP recommends 600,000 for PBKDF2-HMAC-SHA256, not 60,000. The count
is unchanged because raising it would break existing ciphertexts without
a versioned format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VVaw7TAdd8oB3QkggFBkM6
dinwwwh added a commit that referenced this pull request Nov 3, 2026
## Problem and fix

### 1. MessagePort message after close
(`adapters/message-port/handler.ts`)
`close()` removed the port from `peers`. A later `.message(port, ...)`
then created a new `ServerPeer` that was never closed or aborted.

The fix is the same one #2373 made for the WebSocket and crossws
handlers:
- `close()` now stores `null` for the port before awaiting
`peer.close()`.
- When `.message()` sees `null`, it returns `{ matched: true }`. It
doesn't create a peer or run the procedure. `peers` is a `WeakMap`, so
the `null` entry is freed when the port is garbage-collected.
- Side effect: `.message()` now decodes the message before it looks up
or creates the peer, so invalid messages no longer create a peer.

### 2. Wrong security comment (`helpers/encryption.ts`)
The comment called 60,000 PBKDF2 iterations the "OWASP recommended
minimum". OWASP's Password Storage Cheat Sheet recommends **600,000**
for PBKDF2-HMAC-SHA256. This PR only corrects the comment and **does not
change the iteration count**. The encrypted output stores the salt and
IV but not the iteration count, so raising it would make every existing
ciphertext undecryptable. Raising it safely needs a versioned format
that records the parameters. That would be a separate change.

## Tests
- message-port: `.message()` called after `.close()`, or while
`.close()` is still pending, does not run the procedure or post
anything. Both tests fail without the fix.

`pnpm vitest run packages/server/src/plugins packages/server/src/helpers
packages/server/src/adapters/message-port` (366 tests), `pnpm
type:check` and `pnpm lint` all pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VVaw7TAdd8oB3QkggFBkM6

Co-authored-by: Claude <noreply@anthropic.com>
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.

2 participants