npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@viveeditor/collab-server

v1.1.0

Published

Self-hosted WebSocket server for viveEditor collaboration: host authentication, read and write access, limits and persistence hooks.

Readme

@viveeditor/collab-server

Self-hosted WebSocket server for viveEditor collaboration, used with @viveeditor/collab.

Part of viveEditor, a free, open-source rich text editor.

Usage

import { createServer } from 'node:http'
import { createCollabServer } from '@viveeditor/collab-server'
import { basicExtensions } from '@viveeditor/ext-basic'

const collab = createCollabServer({
  origins: ['https://app.example.com'],
  extensions: basicExtensions,
  async authenticate({ token, document }) {
    const session = await verifyToken(token, document)
    if (!session) return null
    return {
      access: session.canWrite ? 'write' : 'read',
      user: { id: session.userId, name: session.name, color: '#1d4ed8' },
      expiresAt: session.expiresAt,
    }
  },
  load: (document) => database.loadDocument(document),
  store: (document, { state, epoch }) => database.saveDocument(document, state, epoch),
})

const server = createServer()
server.on('upgrade', (request, socket, head) => collab.handleUpgrade(request, socket, head))
server.listen(1234)

extensions must be the same list the editor uses; a browser with a different schema is refused.

Example server

The repository has a runnable example in example/ (not part of the npm package). From a clone, after pnpm install and pnpm --filter @viveeditor/collab-server build:

COLLAB_SECRET="$(openssl rand -base64 48)" COLLAB_ORIGINS=https://app.example.com node packages/collab-server/example/server.mjs
  • COLLAB_SECRET (at least 32 bytes; generate it, as above, rather than typing it) signs the tokens. Use a different secret per environment, keep it in your secret store, never in the page or the repository, and replace it if it may have leaked: every token signed with the old one stops working.
  • COLLAB_ORIGINS is a comma-separated list of allowed page origins. PORT (default 1234), HOST (default 127.0.0.1) and COLLAB_AUDIENCE (default viveeditor-collab) are optional.
  • Behind your own reverse proxy, set COLLAB_TRUSTED_PROXY=1 so the per-address limits use the last X-Forwarded-For entry your proxy adds; otherwise every person counts as the proxy's address and one person can use up the limits for everyone. Only set it when the server cannot be reached except through that proxy.
  • WebSocket connections are accepted on /collab only; put the server behind a TLS proxy so browsers connect with wss://.
  • The example uses the basic extensions. For the one-script viveeditor drop-in, pass extensions: classicExtensions (from viveeditor) to startExampleServer or createCollabServer: browser and server must build the same schema, or the sign-in is refused.
  • Documents and comments are kept in memory and are lost when the process stops: replace load, store, loadThreads and storeThreads with your database.
  • startExampleServer also takes limits, passed to createCollabServer as they are.

Your application signs a short-lived token for each person and document with signToken from example/token.mjs (HMAC-SHA256, compared in constant time):

import { signToken } from './token.mjs'

const token = signToken(
  {
    sub: user.id,
    name: user.displayName,
    color: '#1d4ed8',
    aud: 'viveeditor-collab',
    doc: documentId,
    exp: Math.floor(Date.now() / 1000) + 300,
    access: canEdit ? 'write' : 'read',
  },
  process.env.COLLAB_SECRET,
)

signToken adds the issue time (iat). The server refuses a token for another document or audience, without a subject or issue time, issued in the future, already expired or valid for more than five minutes.

Serve tokens from an endpoint of your own application; the browser provider asks it for a fresh one with getToken before the old one runs out:

  • Decide doc, access and moderator on the server from your own permission records for the signed-in user. Never take them from the request: otherwise anyone signed in could ask for write access to any document.
  • Accept only POST from your own pages: check Origin (or Sec-Fetch-Site: same-origin) or require a CSRF token, use SameSite=Lax or Strict session cookies, and send no CORS headers (or exactly one allowed origin, never the request's own origin echoed back). Refuse any request whose Content-Type is not application/json: a plain HTML form can post text/plain across sites without a preflight.
  • Answer with Content-Type: application/json, Cache-Control: private, no-store and X-Content-Type-Options: nosniff, and never redirect.
  • Give each collaboration server its own audience (for example its wss:// origin) and set COLLAB_AUDIENCE to match, so a token sent to the wrong server is useless on the right one.
  • For the one-script viveeditor drop-in, answer { "url": "wss://collab.example.com/collab", "token": "…" }: the editor connects only to the url your endpoint names, never to an address taken from the page, and a renewal that names another server is refused. Answer 401 or 403 when the person may not open the document; the editor then stops asking.

To take someone out of a document at once, call revokeUser(userId) on the object startExampleServer returns: it closes their connections and refuses every token issued before that moment, so a stolen or cached token cannot reconnect. Stop issuing them new tokens in your own system too; a token issued in the same second as the revoke is also refused, so wait a second before issuing a new one if they should come back. The example keeps revocations in memory; keep them in your database (per user, until the longest token has run out) when you run more than one process or restart.

Signing in

The schema fingerprint covers node, mark and attribute names and the options that change what a document may hold (link protocols, heading levels, fonts, alignments, indent depth, image and embed policies, mention label length, table cell width), and each attribute's validator name (the label given to attributeValidator or cleanAttribute, or a string rule) and whether it has a cleaner, but not the validator functions themselves: a function cannot be compared across two builds. A custom extension whose validator depends on its options should return those options from schemaOptions, so the fingerprint changes with them. Build the server with the same extensions and the same configure() options as the editor: a browser whose options differ is refused at sign-in. Fingerprints from versions before 1.0.0-rc.0 do not match the new ones, so update the editor and the server together.

  • The page origin must match one of origins exactly. Requests without an Origin header are refused unless allowMissingOrigin: true.
  • authenticate gets the token the browser sent and returns a grant or null. The grant expires at expiresAt (at most one hour ahead); the browser renews it in place with getToken. A renewed token never raises access; use setAccess for that.
  • revoke({ document?, userId? }) closes matching connections and setAccess(target, 'read' | 'write') changes their access at once, including sign-ins still running. Also invalidate the token in your own system: a revoked person can sign in again for as long as authenticate accepts their token.

Storage

load(document) returns { state, epoch, owners? } or null for a new document; store gets the same shape. owners lists [clientId, userId] pairs, so who wrote under which client id survives a reload; store it as you got it. Documents stored without it start that record again. The epoch tells browsers when a stored document was replaced: return null (or a new epoch) after deleting a document, and browsers drop their local copy. Do the same when you restore a backup: store it with a new epoch so open browsers reset cleanly to the restored document. With the old epoch, a browser that still holds changes the backup lost resends them, the server refuses them with close code 4422, and the browser stops in the diverged state with its own copy available as ProseMirror JSON in provider.localDocument, so the app can offer the text for copying. Changes are stored two seconds after the last edit, at most every 30 seconds while editing continues, when the last person leaves and when close() runs. Stores of one document never overlap: the next one starts after the previous store call has finished.

Run one process per document: two processes serving the same document would each keep their own copy.

Checking changes

Every change a writer sends is checked against the editor schema before it is applied: only the default document, only elements, attributes and marks the schema defines, attribute and mark values that pass the schema's validators, content placed where the schema allows it, new elements carrying every attribute without a default (which no later change may remove, also not by writing a value that is deleted in the same change), marks that may not overlap themselves stored under their own name (only marks that may overlap, such as comments, take the numbered suffix Yjs adds), children in the order their content rule asks for, at most 32 levels deep (limits.depth, by default MAX_EDIT_DEPTH from @viveeditor/core, the deepest content the editor lets anyone make, so an honest writer is never closed for depth; keep limits.depth at least that high), strings of at most 1 048 576 characters and at most 500 000 items or deletions per change (items are counted before the change is decoded). A suggestion must carry the writer's own id and name and a time no more than clockSkew (ten minutes) ahead of the server clock; earlier times are kept, because changes made offline arrive later. Someone else's suggestion can only be moved, so the same change must delete exactly the text it carries, under the same kind of suggestion (a suggested deletion cannot come back as an insertion), and text typed inside someone else's suggestion must not take on their name. The order of moved text is checked within each paragraph, not across them: text deleted from under someone else's suggestion may come back spread over several paragraphs in another order between them, and the text of one of their deleted changed paragraphs may come back split over several new paragraphs that each carry their change. Undoing the deletion of someone else's suggestion is refused for the same reason: it would bring their text back as new text under their name. A change is refused as too large when it keeps more than 256 suggestions open at one point (also when it only adds suggestion marks to existing text), or when checking it takes more work than its size allows. A client id belongs to the first person who writes with it, and nobody else may write or show a cursor under it; the record is stored with the document as owners. A change that fails is not applied and the writer is closed with code 4422; a change over a size limit is closed with code 4413 instead (see Limits).

Stored documents get the same check when they are loaded, without the per-change size limits; a stored document that fails is not opened, and onEvent receives a failed event with stage check so you can repair it. Children added to an element that already exists, or removed from it, are checked against its content rule after the change is applied; a change that leaves such an element out of its rule (for example the only row of a table deleted) is kept, because simultaneous edits by honest writers reach the same states, and onEvent receives a failed event with stage check and the writer's userId (at most once every 10 seconds per writer; elements deleted in the same change are not checked). Before each store the whole document is checked as well; a document that fails is still stored and reported with stage check without a userId. The editor keeps working with such a document.

Comments

Comment threads are shared through the server when you pass both loadThreads(document) (returns the stored list of threads or null) and storeThreads(document, threads). Without them, comment operations are answered with disabled. Threads are stored with the same timing as the document.

The browser sends operations (create, reply, edit, removeComment, resolve, remove) with an operation id. The server writes every new comment and every edit under the signed-in person and the server time, whatever the browser claims, and new threads always start unresolved. People can edit and delete only their own comments, and delete a thread only when all of its comments are theirs; a grant with moderator: true may change any comment. A renewed token can take moderator rights away but never grant them; use setAccess(target, access, { moderator: true | false }) to change them at once. Pass canResolve({ document, user, moderator, thread, resolved }) to decide who may resolve or reopen a thread (everyone with write access by default; if the hook throws or does not answer within two seconds, the change is refused). Readers can read comments but every operation they send is refused.

Each operation is applied in order and shared with everyone in the document; the sender also gets its operation id back, or a refusal (read-only, disabled, invalid, exists, missing, forbidden, full or busy). Limits: 64 KB per operation, five operations a second per connection (20 at once, and at most 20 waiting), 200 threads started per person, 2 MB of comment data per document. loadThreads must return an array: anything else keeps the document from opening, and entries that are not valid threads are dropped. Stored threads larger than 2 MB still open, onEvent receives a failed event with stage threads, and comments can only shrink until they fit.

Presence

Cursors are shared through the server. Each connection may announce at most four client ids; an id another person already uses, or has written changes with while the document is open, is ignored. The server rebuilds every announcement from the signed-in user's name and color and a cursor position inside the shared document; any other field the browser sends, and the user id, are not shared. An id is held for its owner for a minute after their connection closes. Each person's cursor updates are shared at most 20 times a second, and a room's at most 200. Use opaque user ids rather than e-mail addresses: they are stored with comments and suggestions. People who join see who is already there, and everyone is told when someone leaves.

Limits

Every limit has a default in DEFAULT_LIMITS and can be changed through limits. Per-address limits use the socket address (IPv6 grouped by /64). Behind a reverse proxy, pass address: (request) => ... that returns the client address your proxy reports; only trust a forwarded header your own proxy sets.

  • One change may be as large as message (10 MB + 64 KB by default, a little above documentSize, so a whole document can be pasted or opened at once). Keep message at or above documentSize, and let your proxy pass WebSocket messages of that size.
  • Byte rates have a burst and a rate: bytesBurst (10 MB + 64 KB) refills at bytesPerSecond (1 MB a second) per connection and per person, and roomBytesBurst (twice message) at roomBytesPerSecond (5 MB a second) per document. One large change passes; a steady stream past the rate is closed with 4429. When the document budget runs out, only a writer who used more than an even share of it recently is closed; the others keep writing on a slower allowance, so the document takes at most about twice its rate.
  • Documents per person. One person may have roomsPerUser (5) different documents open at once, across all of their connections (connectionsPerUser, 10). A sign-in past either limit is closed with 4429.
  • Document items. A document may hold documentItems (600 000) Yjs items, deleted ones included until they are cleaned up. A 10 MB article is about 240 000 items; many small edits make more items than one large paste.
  • Close codes. 4413 with the reason update means the change was larger than message, a burst, a string, item or deletion limit; 4413 with the reason document means it would make the document larger than documentSize or documentItems. Both are final for that change: the browser keeps it, says so and sends it only when it fits. 4429 is temporary and retried. A 4413 without a reason means a sign-in, presence or comment message was too large.
  • Before sign-in a connection may send only its sign-in message (8 KB); a reader may send at most 64 KB at a time. Any more and the server stops reading and closes it, so a stranger cannot make the server hold a large message.
  • Memory. Incoming messages are held until they are complete, at most message per writer connection. Changes are checked one at a time: a 10 MB change was checked and shared in about one to one and a half seconds on an Apple-silicon Mac. Without workers the process is blocked meanwhile (about 500 to 800 ms for 10 MB, two browser connections included); with workers, only the documents on that worker wait (see Workers). An open document uses roughly six to nine times its stored size (about 9 MB for a 1.4 MB document, about 95 MB for a 10 MB one). Plan for rooms × the open size of your largest documents: the defaults allow 1000 open documents, which at 10 MB each would need about 95 GB, so lower rooms or documentSize to fit your machine. Each connection may queue up to bufferedAmount (14 MB) for a slow reader.
  • Outgoing data. A person may ask for at most outgoingBytes (40 MB) of document state and comment snapshots a minute, across all their connections and documents in the process (it must be at least documentSize); past it the connection is closed with 4429. A reader may also ask for the whole document at most every syncInterval (10 seconds) per connection. Changes and cursors other people make are shared without this limit, and each sign-in sends the document and up to 2 MB of comments; keep connectionsPerDocument and connectionsPerUser in line with your bandwidth.

Workers

Pass workers to check and share changes in worker threads, so one large change does not hold up other documents:

createCollabServer({
  ...options,
  extensions,
  workers: { module: new URL('./schema.js', import.meta.url), count: 2 },
})

module is a file that exports the same extensions you pass to the server (export const extensions = [...]). Validators are functions and cannot be sent to a thread, so each worker imports the file and builds the schema itself; a worker whose schema has another fingerprint than the server's opens no documents. count defaults to one less than the number of processors, at most four. memory caps each worker's heap in megabytes (default 4096, from 64 to 65536); a worker that runs out stops and its documents reconnect, while the main process keeps running. Each document stays on one worker until it unloads; new documents go to the worker with the fewest. Sockets, sign-in, every limit and every hook (load, store, loadThreads, storeThreads, canResolve, onEvent) stay on the main thread. In a test with a 5.7 MB change, another document answered in about 15 ms with workers and about 700 ms without.

If a worker stops, the connections to its documents are closed with 1011, onEvent receives a failed event with stage worker and no document, and a new worker starts (after a growing pause, up to 30 seconds, if it keeps stopping right after starting); browsers reconnect and the documents load again from storage. Changes made since the last store on that worker are lost.

onEvent receives sign-in, refusal, close and failure events for your logs. It never carries tokens or document content.

License

MIT