Skip to content

feat(collab): Hocuspocus 4.7.1 and collab ingress bounds (wiki-v2 #790) - #87

Merged
PMQ9 merged 12 commits into
wiki-v2from
fix/790-hocuspocus-4
Nov 10, 2026
Merged

PMQ9 merged 12 commits into
wiki-v2from
fix/790-hocuspocus-4

Conversation

@PMQ9

@PMQ9 PMQ9 commented Nov 10, 2026 •

Copy link
Copy Markdown

What

This change upgrades collab to Hocuspocus 4.7.1 and bounds the memory a collab client can make the server hold. It fixes https://github.com/cccvu/wiki-v2/issues/790 (wiki-v2 issue 790) and is paired with the super PR https://github.com/cccvu/wiki-v2/pull/811. The design record is the ADR 0036 amendment in the super PR.

The upgrade

  • @hocuspocus/{server,provider,transformer} 3.4.4 → 4.7.1, and @hocuspocus/common 4.7.1 added (RedisSync imports its close events). tseep is dropped; lib0 stays, pinned workspace-wide to 0.2.120 (a pnpm.overrides entry plus the server dep): yjs and y-protocols had resolved 0.2.117, whose decoders read past the end of a frame that is a view into a larger buffer.
  • The server half of upstream a55057db, backported: RedisSync (collab-proxy-socket.ts, redis-sync.types.ts, ws-socket-wrapper.ts byte-identical; redis-sync.extension.ts with three changes) and the gateway.
    • 4.x listens to no socket events, so the gateway drives the returned ClientConnection (handleMessage/handleClose) on both paths, and shutdown calls flushPendingStores().
    • The upstream @tiptap bump and the provider-react rewrite of page-editor.tsx are not taken.
  • RedisSync's three changes. A proxied socket is refreshed with the public touch(), not upstream's write to the private connectionEstablishedAt, which reopened the pre-auth deadline. onSocketOpen returns the connection. And the owner copies a proxied frame (new Uint8Array(message)), as the origin path already did, since msgpackr returns it as a view into the Redis reply.
  • Keepalive. 4.x sends no pings and reaps a socket idle for 60 s. authz/collab-ingress/socket-keepalive.ts pings every 30 s, and each pong calls touch(). An unauthenticated socket still meets its deadline. Each tick also terminates a socket that held a document connection and has held none for two ticks (socket-documents.ts): 4.7.1 leaves the socket up after a document-level close, and the pongs would otherwise keep it open for good.
  • Behaviours kept from 3.4.4 (authz/page-write/, persistence and handler seams):
    • onStoreDocument reads lastContext. Reading the old context throws inside the store, so every store would fail.
    • issue 716 R4. 4.x's DirectConnection.transact() no longer stores. withYdocConnection runs the first store explicitly through the public storeDocumentHooks (direct-store.ts), and disconnect()'s store stays the retry.
    • Only a websocket editor becomes a contributor; 4.x hands a direct connection's context to onChange.
    • The reconcile merge opts out of store scheduling (skipStoreHooks).

authz/collab-ingress/: bounds 4.7.1 leaves open (numbers in limits.ts)

  • ws (collab-ws.adapter.ts, new seam): maxPayload 8 MiB (= PAGE_MAX_YDOC_BYTES_CEILING, close 1009), maxFragments 1024 and maxBufferedChunks 65,536 (close 1008), and a verifyClient (preauth-slots.ts) that refuses the upgrade 503 with Retry-After once 512 unauthenticated sockets are open in the process. The upgrade callback takes the slot and counts the bytes the upgraded TCP socket delivers (Node's public data event) until the first Authenticated reply, a partial frame included: one socket may send a maximal frame (8 MiB, so a busy page's SyncStep1 or a cached page always opens), and all of them together 128 MiB, past which the socket holding the most is terminated. In all, about 128 MiB + 512 × 64 KiB of objects ≈ 160 MiB. A socket not authenticated within 10 s is terminated, and a refused authentication closes the socket (4401) right after its PermissionDenied reply.
  • Hocuspocus options: maxPendingDocuments 1 (one document per socket, as the editor opens), and maxUnauthenticatedQueueSize 8 MiB per socket (ResetConnection past it).
  • frame-address.ts, on every inbound frame before RedisSync or Hocuspocus reads it: the name must be page.<uuid> with a lower-case UUID (Postgres compares uuids case-blind, so an alias would load a second live document), a socket may name at most 4 distinct documents, and send at most 8 Auth frames. A junk or fresh name never becomes a Redis lock key, and a refused token cannot be retried forever on one socket. Past any of them the socket is terminated.
  • The RedisSync socket id is a server-made UUID, never the client's sec-websocket-key.
  • bounded-socket.ts: the socket is terminated rather than queue a frame that would take bufferedAmount past 1 × 8 MiB plus the largest frame sent on it (this one included), so it holds at most 16 MiB of frames up to maxPayload. The keepalive tick also terminates a socket whose non-empty send buffer has not gone down for two intervals (a page that stops reading still answers pings).
  • frame-address.ts also DROPS an Awareness or QueryAwareness frame over the socket's awareness rate (burst 200, then 40/s); the socket stays. Awareness is a last-state channel, so the next frame supersedes a dropped one, and an honest drag selection (one frame per pointer event, at the display's refresh rate) is never refused.
  • auth-rate.ts (authentication extension seam): a per-user bucket (burst 64, 1/s), charged after the JWT verifies and before any DB or permission read. A token that does not verify is refused permission-denied with no message, so Hocuspocus logs nothing per attempt; the client sees the same reason as before.
  • user-connections.ts: at most 32 authenticated collab connections per user per process. Checked in onAuthenticate right after the auth rate, before any read; a gateway extension (priority 9000, below the guard and above RedisSync) holds each connection from connected to onDisconnect and closes one that concurrent authentications took past the cap, then its socket (code 4429).
  • socket-limit-log.ts: one COLLAB_SOCKET_LIMIT line per violation, at most 30 a minute, with numbers and ids only. collaboration.module.ts (new seam) logs a client's ws errors through it as ws_error, with ws's code only, instead of upstream's unrate-limited error line.

The settle: authz/page-write/settle-drain.ts, called from collaboration.handler.ts. 4.x's debouncer deletes a store's timer before that store waits for the one already running, so a queued store was invisible to the old settle: flushPageContent answered flushed:true with the row still stale, and read the failure flag before that store ran. A guarded write's If-Match pre-check could then pass against content the caller never saw (wiki-v2 issue 282's lost update). The settle now runs the pending store, then drains until no store is executing and the mutex is free (at most 32 rounds, fail closed), and reads the failure flag after the last store. The new collab-flush-queued-store.spec.ts reproduces it on real 4.7.1 and goes red without the fix.

update-guard.ts: guard bounds (constants in that file)

  • Sync and new-awareness-id budgets per (user, document), kept across reconnects in one bounded LRU map: a burst of 64 (all 32 tabs of the per-user cap reconnecting at once pass), then one per 4 s. The sync budget counts SyncStep1 and a read-only session's Step2; a reader's Update is not counted. An exhausted budget closes the SOCKET with 1013, which the editor retries; it is never a 4422 refusal.
  • awareness, for readers too: each state ≤ 8 KiB (read from the length prefix before parsing), no client id twice in a frame.
  • foreign-client on awareness: a non-null state for a client id bound to another user is refused; removals and echoes pass. Awareness binds are budgeted at 256 per user per document (was 4096 per document for everyone).
  • auth, message-type: Auth on an established session, and any type 4.7.1 does not handle, are refused.
  • Lazy rebuild. A refusal marks the shadow dirty. A rebuild unbinds the replaced shadow's client id.
  • Hook ban. The wiring spec bans beforeSync and beforeHandleAwareness anywhere in the server: 4.7.1 awaits them between the guard and the apply.

Client editor-ux/

  • page-editor.tsx passes the close code, and collab-access.ts treats close 1009 as a refusal (detach, read-only, the notice). Otherwise the provider resends the same oversized frame every second.
  • On any refusal the editor disconnects its own socket (the new disconnectSocket step), and neither an in-flight token refetch nor the tab becoming visible reopens it. Reload and Discard reload the page, so recovery needs no socket.

Why

The collab server queued frames without bound before auth, after a denied auth and after a CLOSE. It had no auth deadline, a 100 MiB maxPayload, unchecked awareness and no outbound bound. It runs in the process that serves the API, so any client could put that process under memory pressure.

Upgrading closes the pre-auth half upstream, along with GHSA-xwhh-v746-pj9m (pre-auth DoS, affects <= 4.2.0, fixed by Hocuspocus PR 1113 in 4.3.0) and GHSA-8v8m-xjrm-95h6 (BroadcastStateless, patched in 4.1.1), which 3.x will never get. Reimplementing it on 3.4.4 meant inferring ClientConnection's private state from outside. It also makes the next upstream merge smaller, since v0.96 already ships 4.x.

Scope

  • Fork-owned code: authz/collab-ingress/, authz/page-write/ and apps/client/src/features/editor-ux/.
  • Upstream files touched:
    • the documented seams: gateway, handler, persistence, authentication extension, page-editor.tsx;
    • the new seams: the ws adapter and collaboration.module.ts;
    • the package manifests (including the lib0 override) and lockfile;
    • the four redis-sync files (a recorded backport of upstream a55057db).
  • check-upstream-boundary.sh: pass (local, super branch at this head).

Tests

Commits: 12c0c930 (upgrade and backport), 01daa4a6 (store and attribution semantics), bb3508ad (the guard under 4.7.1), 1dd744bf (socket bounds), 428110f9 (guard bounds, client 1009), 337f8964 (the settle drain), 7a21b9ff (review-round fixes), 13c4a448 (review loop round 1: the awareness rate drops instead of refusing, the outbound frame is counted before queueing, empty sockets are reaped), e6b037cc (round 3: the process-wide unauthenticated-socket cap and pre-auth deadline; per (user, document) budgets that close 1013), ba4c385f (round 4: a refused socket is closed and a lost editor retries slowly; the pre-auth byte count and a 512 pool; one document per socket; sync budgeted per user too), 8b453f89 (round 5: a maximal frame per unauthenticated socket, a 128 MiB total, the largest holder cut).

Suite Result
CI FORK_SPEC_ROOTS lane local at 7a21b9f: 252 suites, 4,105 passed, 0 failed. CI: run by the paired PR's ci.yml on each gitlink bump.
pg lane (AUTHZ_REQUIRE_PG=1) local at 428110f: 43/43 suites, 603/603. CI: run by the paired PR's ci.yml on each gitlink bump.
typecheck (both orders) local at 7a21b9f: clean
client vitest local at 7a21b9f: 956 passed
  • Against a real Hocuspocus 4.7.1:
    • a maximal honest frame fits the pre-auth queue, one byte more terminates, and the upstream 5 MiB default would have terminated it;
    • a fifth pending document terminates;
    • a quiet socket is reaped without the keepalive and survives with it;
    • pongs never extend an unauthenticated deadline;
    • a refused token is retried at most 8 times per socket, logs nothing, and the client reads permission-denied (socket-auth-budget.spec.ts).
  • Gateway, both paths:
    • a junk name, or a fifth distinct name, never reaches RedisSync, nor do Auth frames past 8 (upper-case names are refused in frame-address.spec.ts);
    • the socket id is server-made;
    • a non-reading socket is cut off, by size or by the stall check;
    • the connection-cap extension sits second, and at the cap onAuthenticate reads no repo (user-connections.spec.ts);
    • no source reads sec-websocket-key from the client request.
  • RedisSync: the owner decodes a proxied frame inside its bounds, and the server, yjs, y-protocols and Hocuspocus all resolve lib0 0.2.120 (redis-sync-proxy.spec.ts).
  • Persistence: stores land through lastContext, the two-attempt direct store holds, attribution is pinned for API writers, websocket editors and both together, and the version tripwire reads 4.7.1.
  • Guard:
    • honest opens pass for a writer and a reader;
    • each new rule refuses its flood, including a state for another user's id; an awareness flood is dropped at the gateway with the session kept;
    • one writer's binds never use up another user's;
    • bindings stay constant over K refusals.
  • Client: 1009 → refused, and a refused editor disconnects its socket and nothing reopens it. A lost editor (a second refusal, or a refetch that fails) closes its socket too and opens it again after 60 s, or when the tab becomes visible.
  • Each new bound was mutation-checked locally (reverting it fails its specs). The browser collab suite at the paired PR's head before round 1 passed 13/15; the two failures are pre-existing on the base branch.

🤖 Generated with Claude Code

PMQ9 and others added 8 commits November 9, 2026 22:38
…lf (wiki-v2 docmost#790)

- @hocuspocus/{server,provider,transformer} 3.4.4 -> 4.7.1, @hocuspocus/common 4.7.1 added (RedisSync
  imports its close events). The @tiptap bump a55057d bundles is not taken. tseep dropped (its only user,
  the proxy socket, no longer extends an emitter); lib0 kept (the docmost#781 guard decodes frames with it).
- RedisSync and the gateway from upstream a55057d: Hocuspocus 4.x listens to no socket events, so the
  gateway drives the returned ClientConnection (handleMessage/handleClose, a web Request) on both paths,
  and shutdown flushes pending stores. Our seams (#3 guard first, unloadImmediately, tls, #3f, #3g) stay.
- RedisSync refreshes a proxied socket through the public touch() instead of upstream's rewrite of the
  private connectionEstablishedAt, which reopened the pre-auth deadline. onSocketOpen returns the
  connection.
- 4.x sends no pings and reaps a connection idle for `timeout` (60 s). The gateway pings every socket
  (authz/collab-ingress/socket-keepalive.ts, 30 s) and every pong is touch(), as Hocuspocus's own Server
  does; an unauthenticated socket still meets its deadline. Pinned against a real Hocuspocus.
- The collab-ingress testkit's FakeSocket.connect wires a socket as the gateway's standalone path does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…uspocus 4.x (wiki-v2 docmost#790)

- onStoreDocument reads 4.x's `lastContext` (reading the old `context` throws inside the store, which the
  seam records as a failure: every store would fail).
- docmost#716 R4: 4.x's DirectConnection.transact() no longer stores (it schedules a debounced store) and
  disconnect() stores once, so a direct write lost its in-request retry. withYdocConnection runs the first
  store explicitly through the public storeDocumentHooks (authz/page-write/direct-store.ts), with the
  payload disconnect() builds; disconnect()'s store stays the retry. Never rejects.
- Contributors: 4.x hands a direct connection's context to onChange; only a websocket editor counts, as
  under 3.4.4 (persistence-attribution.spec.ts pins both kinds of writer and the broadcast).
- 4.x schedules a store for every change whose origin does not opt out. The docmost#390 reconcile merge runs
  inside a store, so it opts out (skipStoreHooks), as 3.4.4 scheduled nothing for it.
- Specs: the version tripwire is 4.7.1; hand-built payloads and origins take the 4.x shapes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…i-v2 docmost#790)

- 4.7.1 awaits beforeSync / beforeHandleAwareness between the guard and the apply, so the wiring spec now
  bans both hooks anywhere in the server (with an anti-vacuity check of the scan), besides a second
  beforeHandleMessage.
- The ordering comments describe 4.7.1: one frame at a time per connection, frames of different
  connections interleave (the in-flight list is still needed), and a hook rejection drops the
  connection's queued frames (docmost#1123); refusedConnections stays as defense.
- The extension spec's stateless control no longer applies frames queued after a CLOSE, and 4.x merges a
  turn's updates into one broadcast; both asserted as the new behaviour.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… (wiki-v2 docmost#790)

- ws: maxPayload 8 MiB (= PAGE_MAX_YDOC_BYTES_CEILING), maxFragments 1024,
  maxBufferedChunks 65536 on the collab WebSocketServer (new adapter seam).
- Hocuspocus: maxPendingDocuments 4, maxUnauthenticatedQueueSize 8 MiB.
- Gateway: every inbound frame must address page.<uuid> before RedisSync or
  Hocuspocus sees it (a junk name never becomes a Redis lock key); the socket
  id is a server UUID, never the client's sec-websocket-key; outbound writes go
  through BoundedCollabSocket, which terminates a peer that stops draining.
- Auth: a per-user collab auth bucket (burst 64, 1/s) charged right after the
  JWT verifies and before any DB/PDP read.
- One rate-limited log token, COLLAB_SOCKET_LIMIT.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ent treats 1009 as refused (wiki-v2 docmost#790)

- sync-rate: a per-connection bucket for SyncStep1 and a read-only session's Step2 (burst 4, then 1 per 15 s)
- awareness: each state <= 8 KiB (checked on the length prefix), no duplicate client id in a frame,
  <= 32 never-seen client ids per connection; readers included
- auth / message-type: refuse an Auth frame on an established session and any type 4.7.1 does not handle
- lazy shadow rebuild after a refusal; a rebuild unbinds the replaced client id; awareness binds capped at 4096
- client: a socket close with code 1009 (frame over maxPayload) is a refusal, not an endless reconnect

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ight (wiki-v2 docmost#790)

Hocuspocus 4.7.1's debouncer deletes a store's timer before it waits for the
store already executing (3.4.4 deleted it after). While it waits the queued
store is invisible to isDebounced and holds no saveMutex, so flushPageContent
returned flushed:true once the FIRST store finished: the row still lacked what
the queued store carried, and that store's failure was read too early.

authz/page-write/settle-drain.ts runs the pending store once (attribution
unchanged), then drains saveMutex and re-checks at a macrotask boundary until
no store is executing (isCurrentlyExecuting) and the mutex is free, capped at
32 rounds (fail closed). The store-failure read now follows the last store.

collab-flush-queued-store.spec.ts pins it on the real 4.7.1 debouncer: red
(3/3) without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ounds (wiki-v2 docmost#790)

- frame-address: lower-case `page.<uuid>` only (no case alias of a live document); per socket,
  at most 4 distinct document names (before RedisSync claims a Redis lock per name) and 8 Auth
  frames (a refused Auth can otherwise re-run onAuthenticate forever).
- auth: a token that does not verify is refused { reason: 'permission-denied' } with no message,
  so Hocuspocus logs nothing per attempt; the client reads the same reason as before.
- user-connections: at most 32 authenticated collab connections per user per process, held from
  `connected` to `onDisconnect`, checked in onAuthenticate before any read and enforced at
  `connected` for concurrent authentications.
- keepalive: terminate a socket whose non-empty send buffer has not gone down for two ping
  intervals; the outbound allowance is 1 x 8 MiB above the largest frame sent (was 4 x).
- update guard: a per-connection awareness bucket (burst 200, 40/s); no awareness state for a
  client id bound to another user (removals and echoes pass); awareness binds are budgeted per
  user per document (256), not 4096 per document for everyone.
- RedisSync owner copies a proxied frame; lib0 pinned to 0.2.120 workspace-wide (bounds-checked
  views).
- collab module logs a client's ws errors through the rate-limited COLLAB_SOCKET_LIMIT logger.
- client: a refused editor closes its own socket and nothing reopens it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PMQ9
PMQ9 marked this pull request as ready for review November 10, 2026 16:06
PMQ9 and others added 4 commits November 10, 2026 10:44
…ueueing, reap empty sockets (wiki-v2 docmost#790)

Review round 1 of the collab bounds:

- Awareness rate: over-rate Awareness and QueryAwareness frames are now dropped at
  the gateway (admitCollabFrame, per socket, burst 200 then 40/s) instead of refused
  by the update guard. An honest mouse-drag selection sends one frame per pointer
  event at the display's refresh rate, so a refusal could end an honest editor's
  session over a cursor. Awareness is a lossy last-state channel, so a dropped frame
  is superseded by the next one.
- Outbound bound: a frame is counted before it is queued, so a socket never holds
  more than 8 MiB plus its largest frame (it could reach about 24 MiB before).
- Empty sockets: Hocuspocus 4.7.1 leaves the websocket up after a document-level
  close, and the keepalive's pongs kept it open for good. The keepalive tick now
  terminates a socket that held a document connection and has held none for two
  ticks (socket-documents.ts, counted from `connected` to the connection's onClose).
  An over-cap connection at `connected` also closes its socket.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…and awareness-id budgets per user (wiki-v2 docmost#790)

Review round 3, both owner-approved:

- Unauthenticated sockets: at most 16 per process (preauth-slots.ts). The ws
  server's verifyClient refuses the upgrade 503 with Retry-After past the cap,
  before ws builds a socket, so the bound holds for a client that reaches the
  load balancer directly. A slot is held from the connection (BoundedCollabSocket)
  until the first Authenticated reply is sent (which also covers documents a
  RedisSync peer owns) or the close. Each socket holds at most 16 MiB before auth
  (the pre-auth queue plus one partial frame), so the total is 256 MiB. A 15 s
  pre-auth deadline terminates a socket that never authenticates.
- Sync and new-awareness-id budgets move from per connection (refilled on every
  reconnect) to per (user, document), in one bounded LRU map: a burst of 64 (all
  of a user's 32 tabs reconnecting after a deploy pass), then one per 4 s.
  Exhausting one closes the socket with 1013 (Try Again Later), which the editor
  retries with its backoff; never a 4422 refusal. The sync-rate rule is gone.
- Client tests: 1013 and 4429 socket closes are retried, never refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he pre-auth pool (wiki-v2 docmost#790)

Review round 4:

- A refused authentication closes the socket. Hocuspocus 4.7.1 sends
  PermissionDenied and leaves the socket open, so a lost editor's provider,
  reconnecting every second, held a pre-auth slot for as long as the tab stayed
  open; about seventeen such tabs filled the 16-slot pool. BoundedCollabSocket now
  closes the socket (4401) right after the PermissionDenied reply, and it keeps
  its slot only until it has closed (at most 2 s more).
- A lost editor closes its socket and retries after 60 s, or when the tab becomes
  visible again (collab-access lostStep, page-editor timer).
- Unauthenticated sockets: each may receive at most 256 KiB before it
  authenticates, counted on its TCP socket (Node's public data event, so a partial
  frame ws is still assembling counts too), and the pool grows to 512 with a 10 s
  deadline: 512 x (256 KiB + objects) is about 160 MiB. The edge's per-address
  rate lets one address hold about 67 at a time. The slot is now taken in the ws
  adapter's upgrade callback, not in BoundedCollabSocket's constructor.
- One document per socket (maxPendingDocuments 1): after a socket's first
  authentication, 4.7.1 applies no deadline to a second document's pre-auth queue.
  The pre-auth queue is 256 KiB.
- Sync is also budgeted per user across pages (burst 64, then one a second), so a
  new page does not buy a new burst.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…et across them (wiki-v2 docmost#790)

Review round 5. The 256 KiB per-socket pre-auth cap counted the honest
SyncStep1, which carries the page's whole state vector (about 7 bytes for every
client id that ever wrote to the page, never pruned), and a page's cached copy
that the local store loads after the socket opens. A page many sessions wrote to
would have been cut off for every editor.

One unauthenticated socket may now send a maximal frame (8 MiB, maxPayload) before
it authenticates, and all of them together at most 128 MiB: past that the socket
holding the most is terminated until the total is under, so a client that fills
the budget loses its own largest sockets, not the honest small ones. The memory
bound is unchanged (128 MiB + 512 x 64 KiB of objects, about 160 MiB). The
Hocuspocus pre-auth queue is back to 8 MiB.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@PMQ9
PMQ9 merged commit 18321ce into wiki-v2 Nov 10, 2026
@PMQ9
PMQ9 deleted the fix/790-hocuspocus-4 branch November 10, 2026 21:07
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