Skip to content

fix: secure SIWE nonces and stop socket, polling, and cache leaks - #5523

Closed
jxom wants to merge 3 commits into
mainfrom
fix/memory-reliability-and-siwe-nonce
Closed

jxom wants to merge 3 commits into
mainfrom
fix/memory-reliability-and-siwe-nonce

Conversation

@jxom

@jxom jxom commented Nov 15, 2026

Copy link
Copy Markdown
Member

Fixes found in a performance and memory audit of Viem. Each fix has a regression test that fails without it.

Security

  • generateSiweNonce was predictable. It returned uid(96), which reads a Math.random buffer through a window that slides one character per call, so consecutive nonces shared 95 of their 96 characters. It now uses crypto.getRandomValues (via ox/Hex).

Reliability and memory

  • WebSocket and IPC reconnects stalled after one failed attempt. A failed socket reports its error and close while the reconnect attempt is still in progress, so neither scheduled the next attempt. The client stayed cached for the URL, so every later request failed, even from new clients and after the node recovered, and its keep-alive interval kept the process alive. Now a failed attempt schedules the next one. Once attempts run out, the client is removed from socketClientCache and its keep-alive interval stops.
    • Before: attempts 3, delay 50ms, 1.5s outage → 2 attempts, client still cached, requests fail after recovery.
    • After: 3 attempts, then the client is evicted and a fresh one works. A short outage still reconnects the same client.
  • IPC ignored a graceful close (FIN, e.g. a node shutting down cleanly). getSocket never wired onClose, so in-flight requests hung until their timeout and no reconnect started. Also fixes socket.off('message'), which should be 'data'.
  • IPC subscriptions opened a second socket. subscribe and getRpcClient called getIpcRpcClient(path) without reconnect, so they got a different cache entry, and the subscription socket ignored the reconnect policy.
  • waitForTransactionReceipt kept polling after timing out. If the timeout fired during the first receipt lookup, the timer ran before watchBlockNumber existed. The poll then started anyway and never stopped: about 168 requests/s for 50 timed-out waits.
  • withCache and eip1559NetworkCache were unbounded maps keyed by client.uid, adding one entry per client or client.scope(): +23.7MB per 100k clients. They are now LruMap(8192) and LruMap(128), matching supportsFillTransaction.

Left for follow-ups

These were found in the same audit but need a design decision:

  • fallback({ rank }): ranking never stops after the client is dropped; noticing a dropped client needs WeakRef or an explicit stop.
  • No subscribe/unsubscribe timeout: a timeout that rejects unsubscribe could surface as an unhandled rejection in watchers.
  • supportsExecutionMode caches with cacheTime: Infinity: the result goes stale after a delegation change. This PR's LRU bounds its memory.

Verification

  • New tests fail on main:
    • connections 2 vs 4
    • TimeoutError vs SocketClosedError
    • shared nonce window true
    • 15–17 polling requests after timeout
    • 2 IPC connections
    • responseCache.size 8200
  • Passing: src/utils/rpc, src/clients/transports, src/utils/promise, src/utils/siwe, getBlockNumber, watchBlockNumber, waitForTransactionReceipt and prepareTransactionRequest.
  • Two existing tests failed locally:
    • prepareTransactionRequest > with eth_fillTransaction > args: maxFeePerGas (under default tip) fails identically on main with anvil 1.9.0.
    • waitForTransactionReceipt > waits for confirmations failed a wall-clock bound under load (6,546 ms vs 6,500 ms) and passes in isolation.
  • pnpm check:types and biome check pass.

- `generateSiweNonce` now draws from `crypto.getRandomValues`. It used
  `uid(96)`, whose `Math.random` window slid one character per call, so
  consecutive nonces shared 95 of 96 characters.
- WebSocket and IPC clients keep reconnecting after a failed attempt. The
  failed socket's error and close events arrived while the attempt was in
  progress, so reconnection stalled and the dead client stayed cached for
  the URL. Once attempts run out, the client is dropped from the cache and
  its keep-alive interval stops.
- IPC clients handle a graceful close: pending requests reject with
  `SocketClosedError` instead of waiting for their timeout, and reconnect
  starts. IPC subscriptions and `getRpcClient` reuse the socket configured
  with `reconnect` instead of opening a second one.
- `waitForTransactionReceipt` no longer starts polling when its timeout
  fires during the first receipt lookup.
- `withCache` and the EIP-1559 network cache are bounded LRUs; both grew by
  one entry per client.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2
Co-authored-by: jxom <[email protected]>
@vercel

vercel Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
viem Error Error Nov 15, 2026 11:59pm UTC

Request Review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T23:57:44.488361Z 0a62e65 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@changeset-bot

changeset-bot Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 0a62e65

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
viem Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 60b7e9d655

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/utils/rpc/socket.ts
Comment on lines +179 to +181
keepAliveTimer && clearInterval(keepAliveTimer)
if (socketClientCache.get(id) === socketClient)
socketClientCache.delete(id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Defer cache eviction until the final reconnect actually fails

With reconnect: { attempts: 1 }, a WebSocket disconnect reaches this eviction branch before its reconnect attempt even starts: attemptReconnect() increments reconnectCount, then calls socket.close(), whose implementation in src/utils/rpc/webSocket.ts synchronously invokes onClose_() and re-enters attemptReconnect(). Because the count now equals the limit, this branch deletes the cached client despite the pending reconnect. If that reconnect succeeds, setup() restarts its keep-alive interval without restoring the cache entry, so subsequent transport requests open another socket while the recovered socket remains alive. Check reconnectInProgress before the exhaustion branch and evict only after the final attempt has actually failed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 7d8b0fe: a re-entrant call while the last attempt is pending now returns early, so eviction waits until that attempt fails. Covered by reconnects the cached client when the last attempt succeeds in src/utils/rpc/webSocket.test.ts, which failed before the fix.

Comment thread src/utils/rpc/socket.test.ts Outdated
Comment on lines +1083 to +1086
return {
close() {},
ping() {
pings++

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Exercise reconnect exhaustion against a real ephemeral server

The new reconnect regression test supplies a fake socket with no-op close() and request() methods, contrary to the root AGENTS.md prohibition on mocks and stubs. In particular, the no-op close() omits the production WebSocket wrapper's synchronous close callback, so this test cannot expose eviction caused by re-entering attemptReconnect() when the last attempt is scheduled. Replace the fabricated socket with a real ephemeral WebSocket or IPC server and verify recovery and exhaustion through observable connection behavior.

AGENTS.md reference: AGENTS.md:L155-L158

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Replaced in 7d8b0fe: the stub-socket test is gone, and reconnect recovery and exhaustion are now tested against a real ws server in src/utils/rpc/webSocket.test.ts.

The WebSocket wrapper's `close()` calls back into `attemptReconnect()` while
the final attempt is pending, so the client was evicted even when that
attempt then succeeded. Eviction now waits until the last attempt fails.

The reconnect tests now run against a real `ws` server instead of a stub
socket.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2
Co-authored-by: jxom <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7d8b0fe27f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/utils/rpc/socket.ts
Comment on lines +182 to +183
if (socketClientCache.get(id) === socketClient)
socketClientCache.delete(id)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Guard stale clients against evicting their replacements

After a disconnect with reconnect: false, or after reconnect attempts are exhausted, this eviction allows another request to cache a replacement client. If the caller subsequently cleans up the old client with oldClient.close(), that method still unconditionally calls socketClientCache.delete(id), removing the live replacement's entry. The following request then opens another connection while the replacement remains alive and potentially retains its keep-alive interval. This reproduces against a real ephemeral TCP server. Apply the same client-identity guard to cache deletion in close() so cleaning up an evicted client cannot evict its replacement.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in the latest commit: close() now only deletes the cache entry if it still points to this client. Covered by closing an evicted client keeps its replacement cached in src/utils/rpc/webSocket.test.ts, against a real ws server.

)({ hash }).catch(() => undefined)

if (signal?.aborted) return
if (signal?.aborted || timedOut) return

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve shared receipt lookups for callers that have not timed out

When two calls use the same client, hash, and options without an abort signal, observe() shares the first call's lookup, but their timeout deadlines differ if they start at different times. For example, with timeout: 100, calls starting at 0 ms and 60 ms share a receipt lookup that returns successfully at 120 ms. The first caller's timeout removes only its own listener, but this new guard then abandons the shared lookup because it captures that caller's timedOut flag. The second caller consequently times out at 160 ms even though the receipt arrived within its deadline; previously emit.resolve(receipt) resolved it. Stop the lookup only when no active observers remain, or isolate calls whose timeout lifetimes differ.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in the latest commit: a receipt from the first lookup resolves every caller sharing the observer, and the timeout only stops polling from starting afterwards. Covered by args: timeout (a caller sharing the first receipt lookup keeps its own deadline), which failed before the fix.

@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Published [email protected] under the pr-5523 dist-tag, which follows this pull request until it closes.

pnpm add viem@pr-5523
pnpm add [email protected]

- A receipt found by the first lookup now resolves every caller sharing
  the observer, even when the first caller already timed out. The timeout
  only stops polling from starting afterwards.
- Closing a socket client that was already evicted no longer evicts the
  client that replaced it.
- Added `@types/ws` for the WebSocket server used in the reconnect tests.

Amp-Thread-ID: https://ampcode.com/threads/T-01a1e11e-d5d8-712a-b0ce-513efc7078b2
Co-authored-by: jxom <[email protected]>

jxom commented Nov 16, 2026

Copy link
Copy Markdown
Member Author

Bundled into #5543 as its own commit, so this PR is superseded. Closing in favour of the bundle.

@jxom jxom closed this Nov 16, 2026

This branch had an error being deployed

1 failed deployment
Preview — 0a62e65a Deployed Nov 15, 2026 by vercel[bot]
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