Repository navigation
feat(collab): Hocuspocus 4.7.1 and collab ingress bounds (wiki-v2 #790) - #87
Merged
Merged
Conversation
…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]>
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
marked this pull request as ready for review
November 10, 2026 16:06
…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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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/common4.7.1 added (RedisSync imports its close events).tseepis dropped;lib0stays, pinned workspace-wide to 0.2.120 (apnpm.overridesentry 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.a55057db, backported: RedisSync (collab-proxy-socket.ts,redis-sync.types.ts,ws-socket-wrapper.tsbyte-identical;redis-sync.extension.tswith three changes) and the gateway.ClientConnection(handleMessage/handleClose) on both paths, and shutdown callsflushPendingStores().@tiptapbump and the provider-react rewrite ofpage-editor.tsxare not taken.touch(), not upstream's write to the privateconnectionEstablishedAt, which reopened the pre-auth deadline.onSocketOpenreturns 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.authz/collab-ingress/socket-keepalive.tspings every 30 s, and each pong callstouch(). 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.authz/page-write/, persistence and handler seams):onStoreDocumentreadslastContext. Reading the oldcontextthrows inside the store, so every store would fail.DirectConnection.transact()no longer stores.withYdocConnectionruns the first store explicitly through the publicstoreDocumentHooks(direct-store.ts), anddisconnect()'s store stays the retry.onChange.skipStoreHooks).authz/collab-ingress/: bounds 4.7.1 leaves open (numbers inlimits.ts)collab-ws.adapter.ts, new seam):maxPayload8 MiB (=PAGE_MAX_YDOC_BYTES_CEILING, close 1009),maxFragments1024 andmaxBufferedChunks65,536 (close 1008), and averifyClient(preauth-slots.ts) that refuses the upgrade 503 withRetry-Afteronce 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 publicdataevent) until the firstAuthenticatedreply, 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 itsPermissionDeniedreply.maxPendingDocuments1 (one document per socket, as the editor opens), andmaxUnauthenticatedQueueSize8 MiB per socket (ResetConnection past it).frame-address.ts, on every inbound frame before RedisSync or Hocuspocus reads it: the name must bepage.<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.sec-websocket-key.bounded-socket.ts: the socket is terminated rather than queue a frame that would takebufferedAmountpast 1 × 8 MiB plus the largest frame sent on it (this one included), so it holds at most 16 MiB of frames up tomaxPayload. 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.tsalso 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 refusedpermission-deniedwith 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 inonAuthenticateright after the auth rate, before any read; a gateway extension (priority 9000, below the guard and above RedisSync) holds each connection fromconnectedtoonDisconnectand closes one that concurrent authentications took past the cap, then its socket (code 4429).socket-limit-log.ts: oneCOLLAB_SOCKET_LIMITline 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 asws_error, with ws's code only, instead of upstream's unrate-limited error line.The settle:
authz/page-write/settle-drain.ts, called fromcollaboration.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:flushPageContentansweredflushed:truewith 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 newcollab-flush-queued-store.spec.tsreproduces it on real 4.7.1 and goes red without the fix.update-guard.ts: guard bounds (constants in that file)awareness, for readers too: each state ≤ 8 KiB (read from the length prefix before parsing), no client id twice in a frame.foreign-clienton 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.beforeSyncandbeforeHandleAwarenessanywhere in the server: 4.7.1 awaits them between the guard and the apply.Client
editor-ux/page-editor.tsxpasses the close code, andcollab-access.tstreats close 1009 as a refusal (detach, read-only, the notice). Otherwise the provider resends the same oversized frame every second.disconnectSocketstep), 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
authz/collab-ingress/,authz/page-write/andapps/client/src/features/editor-ux/.page-editor.tsx;collaboration.module.ts;lib0override) and lockfile;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).FORK_SPEC_ROOTSlaneci.ymlon each gitlink bump.AUTHZ_REQUIRE_PG=1)ci.ymlon each gitlink bump.permission-denied(socket-auth-budget.spec.ts).frame-address.spec.ts);onAuthenticatereads no repo (user-connections.spec.ts);sec-websocket-keyfrom the client request.redis-sync-proxy.spec.ts).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.🤖 Generated with Claude Code