Authorization
Decide who may open a document with authorize, bind client ids to users, grant read, comment, suggest or write access, change it, and check origins.
The room enforces identity, but it does not know your users. You tell it who is connecting in authorize, a function routeDocumentSocket calls before it opens a socket. This page covers what authorize returns, how identity reaches the room, and how the room ties every edit to a user.
authorize
type AuthorizeDocumentSocket = (
request: Request,
documentId: string
) =>
| DocumentIdentity
| ExpiredCredential
| null
| Promise<DocumentIdentity | ExpiredCredential | null>;
type DocumentIdentity = {
userId: string;
replica?: number | null;
access?: 'read' | 'comment' | 'suggest' | 'write';
readOnly?: boolean;
expiresAt?: number | null;
};
type ExpiredCredential = { expired: true };
authorize receives the client’s original upgrade request (with its query string and cookies) and the document id you passed to routeDocumentSocket. Return null to refuse. The room is never reached: routeDocumentSocket accepts the upgrade and closes it at once with code 4403 and reason document access denied. A browser reports an HTTP 403 at the upgrade as a bare 1006, the same as a network failure; the 4403 close lets the provider tell a denial from being offline. The provider treats it as final: it emits refused once and stops dialing (see refusals).
Return { expired: true } when the credential was valid but has expired. The dial is accepted and closed with 4401 and reason expired, and the room is never reached. The provider does not stop: it emits expired, then redials after its backoff, reading params again. Put a fresh token in params when expired fires and the next dial gets in.
| Field | Type | Description |
|---|---|---|
userId |
string |
The verified user: any string of 1 to 256 characters with no lone surrogate, reaching the room as is (spaces included). The room binds every client id this socket writes under to this user. |
replica |
number | null |
The client’s CRDT client id (document.clientID), usually read with requestedReplica(request). When omitted, the socket’s first presence message binds it. |
access |
DocumentAccessLevel |
What the user may do: read, comment, suggest or write (the default). See access levels. |
readOnly |
boolean |
true is access: 'read': refuse every write on this socket. Reads and presence still work. Ignored when access is given. |
expiresAt |
number | null |
When the credential expires, in ms since the epoch (a JWT’s exp × 1000). The room closes the socket with 4401 then, and the provider redials with the params it reads again; a dial already past it is closed 4401. Omitted: the socket keeps its access until it closes or you revoke it. |
The document id is the room id the client dials: any string of 1 to 256 characters except ., .. and one with a lone surrogate (a URL collapses those segments, and cannot encode a lone surrogate, so the provider refuses them), which the provider percent-encodes into one path segment. Decode it with decodeURIComponent before you pass it, and close a segment that does not decode with 4400, as the quick start does: no provider sends one.
A plain GET <room>?lastUpdated (no upgrade) is the room’s lastUpdated probe: routeDocumentSocket runs authorize on it as on a dial and answers { "lastUpdated": … } as JSON (the room’s last stored change, ms since the epoch, or null), opening no document; a denial is a plain 403, an expired credential 401 and an invalid id 400. A plain GET <room>?snapshot is the documentSnapshot probe, authorized and refused the same way: it answers { "lastUpdated": …, "document": … }, the room’s document as JSON (it wakes the room; 503 while the room cannot load its document). Any identity authorize admits, a read-only one included, may read it.
routeDocumentSocket answers without calling the room when the request is not a WebSocket upgrade (426, the probe aside), when the document id is empty, ., .., longer than 256 characters or holds a lone surrogate (closed 4400), when authorize returns { expired: true } or an expiresAt already past (closed 4401), or when it returns null or an invalid identity (closed 4403).
| Close | Sent when | The provider |
|---|---|---|
4400 invalid document id |
The document id is empty, ., .., longer than 256 characters or holds a lone surrogate; authorize is not called. |
Final: emits refused and stops dialing. |
4401 expired |
authorize returned { expired: true }, or an expiresAt already past; or the room: the socket’s expiresAt passed. |
Emits expired and redials after its backoff, with params read again. |
4403 document access denied |
authorize returned null or an invalid identity: a userId that is empty or not a string, over 256 characters or with a lone surrogate, a replica that is not a client id, or an expiresAt that is not a finite number. |
Final: emits refused and stops dialing. |
4403 origin not allowed |
The request’s Origin is not one allowedOrigins lists; authorize is not called. |
Final: emits refused and stops dialing. |
4403 access revoked |
The room: closeUser or setAccess(user, 'none'). |
Final: emits refused and stops dialing. |
1012 access changed |
The room: setAccess to another level, except a writer’s down to read. |
Redials at once, so authorize grants the new access. |
4409 replica bound to another user |
The room: the dial’s replica belongs to another user (see replicas). | Final: emits refused and stops dialing. |
4413 quota: <name> |
The room: a write past a quota (document, rate, frame). |
Final: emits refused and stops dialing. |
Your Worker may turn a dial away itself, before routeDocumentSocket: a document that does not exist, an origin you do not serve. Answer the upgrade with closedSocket(code, reason) from edytor/cloudflare rather than an HTTP error, which the browser reports as 1006 and the provider redials forever. It accepts the upgrade and closes it at once with code: use a 4xxx code other than 4401 for a final refusal (4404 for a document that does not exist, say), or 1011 for a fault the provider should retry.
if (!(await documentExists(documentId))) return closedSocket(4404, 'unknown document');
Access levels
access is what the user may do in the document. The room enforces it on every frame, and tells the socket its level as it joins: the document holds it as document.access, which the shared suggestions plugin (a suggest user always suggests, and decides nothing) and the comments plugin read.
| Level | Reads, presence | Comments | Suggests | Edits, decides suggestions, restores versions |
|---|---|---|---|---|
read |
yes | reads them | no | no |
comment |
yes | yes | no | no |
suggest |
yes | yes | yes | no |
write |
yes | yes | yes | yes |
readis a read-only socket.commentis a read-only socket that may post to the comments route: a new thread’s request carries the anchors of the text it is on, and the room writes the thread’s anchor marks itself, since the socket may not. Render the user’s viewreadonly: its comments plugin still starts and answers threads.suggestwrites only suggestions: its view, which needs the shared suggestions plugin, is always in suggesting mode and decides nothing. The room keeps from its frames only what a suggestion is: its suggestion records, their text and blocks, their proposals, deletes of its own suggestion’s content and the binding of its suggestion writers to the user. Anything else (its replica’s direct edits, a decision in another author’s suggestion, a mark on another’s block) is stripped from the frame, the rest applied, and refused with apermission-deniedreply (suggest-only, logged as asuggest-onlyentry in the room’s refusals); the socket stays open, and the provider does not count it as a failure. Its comments are written by the room, as acommentuser’s.writemay do everything, accept and reject suggestions included. A version restore and its undo needwrite(403otherwise).
Revoking access
authorize runs at each dial; an open socket keeps the access it was granted. When a user’s access to a document changes, tell the room, over Durable Object RPC from wherever your application changes it:
const room = env.ROOMS.getByName(documentId);
await room.setAccess(userId, 'read'); // 'write', 'suggest', 'comment', 'read' or 'none'
await room.closeUser(userId); // every socket of the user, 4403 'access revoked'
setAccess(userId, 'read')downgrades each of the user’s write sockets in place: the room sends it the read-only notice (the provider’sreadOnlyturnstrue) and denies every write it sends from then on. The socket stays open.setAccess(userId, level)to any other level (write,suggest,comment, orreadfromsuggestorcomment) closes each of the user’s sockets at another level with1012(access changed). The provider redials at once, andauthorizegrants the new access, so make it return the new access before you call this.setAccess(userId, 'none')andcloseUser(userId)close every socket of the user with4403(access revoked), which stops the provider.closeUser(userId, code, reason?)takes another close code:4401makes the provider redial with freshparams(sign-out, a rotated token),1011makes it redial with backoff. The code must be one a socket can be closed with (1000,1011,1012or3000to4999) and the reason at most 123 UTF-8 bytes: anything else throws aRangeErrorbefore any socket is touched.
Each returns { sockets }, how many it changed, and is logged as an access entry in the room’s refusals (access: the level set, none, or closed for closeUser). Both read the sockets’ attachments, so they work on a hibernated room. With attachDocument, call them on the returned document.
For credentials that expire, return expiresAt from authorize: the room closes the socket with 4401 (expired) at its first message past that time, or on its alarm when the socket stays silent, and the provider emits expired and redials with its params read again. Put the refreshed token in params when expired fires (or before), as for an expired dial.
Example: a signed token
Browsers cannot set headers on a WebSocket, so send a token as a query parameter (or rely on a cookie). This example verifies a JWT with jose and looks up the user’s access to the document in your own data:
import { jwtVerify } from 'jose';
import { DocumentRoom, closedSocket, requestedReplica, routeDocumentSocket } from 'edytor/cloudflare';
export { DocumentRoom };
type Env = {
ROOMS: DurableObjectNamespace<DocumentRoom>;
JWT_SECRET: string;
};
// Your permission model: one of the room's levels, or null.
declare function accessTo(
env: Env,
userId: string,
documentId: string
): Promise<'write' | 'suggest' | 'comment' | 'read' | null>;
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const match = /^\/rooms\/([^/]+)$/.exec(new URL(request.url).pathname);
if (!match) return new Response('not found', { status: 404 });
let documentId: string; // the provider percent-encodes the room id
try {
documentId = decodeURIComponent(match[1]);
} catch {
return closedSocket(4400, 'invalid document id');
}
return routeDocumentSocket(request, env.ROOMS, documentId, async (request, documentId) => {
const token = new URL(request.url).searchParams.get('token');
if (!token) return null;
try {
const { payload } = await jwtVerify(token, new TextEncoder().encode(env.JWT_SECRET));
if (typeof payload.sub !== 'string') return null;
const access = await accessTo(env, payload.sub, documentId);
if (!access) return null;
return {
userId: payload.sub,
replica: requestedReplica(request),
access,
// The socket closes (4401) when the token expires; the provider redials with a fresh one.
expiresAt: typeof payload.exp === 'number' ? payload.exp * 1000 : null
};
} catch (error) {
// An expired token is retried (4401) once `params` holds a fresh one; a forged one is refused (4403).
return (error as { code?: string }).code === 'ERR_JWT_EXPIRED' ? { expired: true } : null;
}
});
}
} satisfies ExportedHandler<Env>;
The client sends the token; the provider adds its replica id (?replica=<clientID>) at every dial:
<script lang="ts">
import { Edytor } from 'edytor';
let { documentId, token, userId }: { documentId: string; token: string; userId: string } = $props();
</script>
<Edytor server="wss://rooms.example.com/rooms" room={documentId} params={{ token }} actor={{ id: userId }} />
params is read at every reconnect; pass a new token to refresh an expiring one (see WebSocket options). An expired token closes the dial with 4401: the provider emits expired (the view’s onSyncExpired) and dials again with the params it then reads, so refresh token there or before it expires. A denied dial (4403) stops the provider: once the permission is fixed, reload the page, or call connect() on a WebsocketProvider you created, to dial again. With a session cookie instead, read request.headers.get('Cookie') in authorize and look the session up; the cookie is sent with the upgrade when the Worker is on the same site, and then set allowedOrigins.
Origins and cookies
Every router (routeDocumentSocket, routeDocumentHistory, routeDocumentComments) takes a last options argument, RouteDocumentOptions:
routeDocumentSocket(request, env.ROOMS, documentId, authorize, {
allowedOrigins: ['https://app.example.com']
});
routeDocumentHistory(request, env.ROOMS, documentId, authorize, {
allowedOrigins: (origin) => origin.endsWith('.example.com')
});
allowedOrigins is a list of page origins (scheme, host and port, as the Origin header carries them) or a predicate over the Origin header. A request whose Origin it does not allow is refused before authorize runs: a dial is closed with 4403 (origin not allowed), which stops the provider, and an HTTP request (the lastUpdated and snapshot probes, every history and comments request) is answered 403. A request without an Origin header passes: browsers send one with every WebSocket dial and every cross-origin request, so only a non-browser client omits it, and such a client cannot carry your user’s cookies. Without the option, every origin passes.
How identity reaches the room
After authorize succeeds, routeDocumentSocket builds a new request for the room (rooms.getByName(documentId), a DocumentRoom or any object with attachRoom) that carries only the verified identity:
| Header | Value |
|---|---|
X-Edytor-User |
userId, percent-encoded (encodeURIComponent) |
X-Edytor-Replica |
replica, when known |
X-Edytor-Access |
read, comment, suggest or write |
X-Edytor-Expires |
expiresAt, when given |
Every header the client sent is dropped, cookies and tokens included, and so are forged X-Edytor-* headers. The room trusts these headers without checking anything else, and refuses a request without them (401).
Replicas
Every browser tab has a CRDT client id (document.clientID, the replica), and every piece of content records the client id that wrote it. The room makes sure nobody writes under a client id that is not theirs:
- Each client id is registered to one user. The registration is stored in the room beside the document, and
onSavereceives it asreplicas: store it withupdateand return both fromonLoad, or a restored room cannot tell who owns which id. - The socket’s own replica (from
authorize, or bound by its first presence entry) is registered when the socket opens, for read-only sockets too, so nobody can take a viewer’s id before it is granted edit. A dial whose replica another user owns is accepted, then closed with4409(replica bound to another user); the provider treats it as final. - A user may write under every id registered to them. A reloaded page gets a new client id, and the edits its earlier id made offline are still delivered on reconnect.
- Content under a client id another user owns, or under an unregistered id that already has content, is stripped from the update (logged as a
replicarefusal, with the id). So are the update’s deletes of the entries the stripped content replaces, whether or not the room still holds them (a changed attribute keeps its stored value, or arrives intact with its author, instead of being emptied). The rest of the update is applied, including its deletes of that id’s items, since anyone who may write may delete: the socket stays connected and its own edits are stored. A delete of an item the room does not hold yet is stored too and waits for that item: it applies when the item arrives. - Content under an id the room holds nothing of, and no user owns, is relayed content: another replica’s edits, which this client received and passes on (edits restored from a local copy, or edits a room restored from an older snapshot lost). It is stored, logged as
relayed, and the id stays unowned: only a socket whose own replica is that id claims it (logged asorphan). Delivering an id never makes it yours.
requestedReplica(request, param = 'replica') reads the replica from the query string and returns null when it is missing or not a valid client id. The shipped provider sends it at every dial. Without a replica from authorize, the socket’s first presence entry binds it (and registers it, as a dial would); until then, the room cannot tell the socket’s own id from one it relays, so an unregistered id without content that the socket writes under is registered to its user.
Registrations of ids that hold no content and belong to no open socket are dropped when the room compacts. After a restore from a bare update (no replicas), each id that holds content is unowned until a signed-in writer dials with it.
Restoring from an older snapshot
If the room’s storage is lost and onLoad returns a snapshot older than the last edits, clients still hold edits the room lacks, including other users’ edits they received. Their handshake delivers them:
- Edits under an id another user owns, or under an id the room already holds part of, are stripped. The author’s own client delivers them when it reconnects. The relaying client’s own edits are stored meanwhile, its deletions of the author’s text included.
- A deletion of text the room lost is stored and waits for it (up to 1,024 waiting ranges per room, see storage): when the author’s client returns with that text, it arrives deleted, for the room, the other clients and the author. A deletion past that limit is dropped, and the relaying client stays unsaved until a later connection gets it stored.
- An edit of its own that builds on stripped content waits in the room’s memory until the author’s edit arrives, with its replacement of any attribute value it rewrites. That memory does not survive the room hibernating or being evicted; the edit reaches the room again at that client’s next connection (or its next
resyncIntervalhandshake). - Any edit of a block whose last change was stripped builds on it, since every edit rewrites the block’s last-changed-by attribute: that client stays unsaved until the author returns and its own edit is in the room.
- Edits under an id the room holds nothing of are stored as relayed content, and the id stays claimable by its author’s dial.
Every author keeps their client ids, and nobody is disconnected for relaying. The relaying client’s saved turns true once the room has stored its user’s edits (its waiting deletions included, even when other edits wait on its own; never one the room dropped), after a reload too: it tracks what that user’s client ids wrote (the document binds each id to its actor), not the stripped edits of others it received earlier.
Because client ids belong to users, a browser profile’s local copy and cross-tab channel should belong to one user. See one user per browser profile.
Attribution trust
Every edit is tied to a client id, and the document’s attribution root binds each client id to an actor (c/<clientID>, read by attribution.actorOf and the provider’s saved) and holds each actor’s profile (u/<actorId>, its name and color). A client writes its binding with its first edit, in the same update, so a socket that only reads stores nothing, and the rules below apply to the update that first writes under a client id. The room checks both against the socket’s verified user:
- A replica binds only itself, to its user. An update that writes
c/<n>under another client id thann, or binds a client id of another user, has that entry removed (its clock kept, the rest of the update applied). When a socket binds one of its own user’s client ids to another actor (an anonymous document, or an actor id that is not the user id), the room applies it, then writes the binding again with the verified user, for every replica including the sender. A binding that names the client id’s registered owner stands whoever wrote it, since it says what the room already holds: the room’s own rewrite, relayed by a replica to a room that lacks it (a reset container, a restore from an older snapshot), is kept. - A user writes only their own profile. An update that writes
u/<id>for another user has that entry removed; the rest applies. - Nobody deletes another’s entry. A delete of another user’s profile, or of the binding of a client id the sender does not own, is dropped.
- Relayed content is stored, its binding waits for its author. When a client relays another replica’s edits (an id the room holds nothing of, see replicas), the room stores them but cannot vouch for their binding to another user, so it removes that binding too. When the author’s own client dials with that id and claims it, the room binds the id to the author.
- Presence names the verified user. The room relays every presence state that names an actor (views always do) with
actor.idset to the socket’s user, whatever the client sent; the other fields (user, the selection) are relayed as sent, and a state withoutactorclaims no identity.
Each removal is logged as a forged entry in the room’s refusals ({ user, keys }). The socket stays connected.
So make the document’s actor.id the userId your authorize returns: createDocument({ actor: { id: userId } }), or <Edytor actor={{ id: userId }}>. With another actor id, the room rebinds the client’s ids to the user id, while the block records still name the actor id, and the client’s own profile (u/<actorId>) is refused as another user’s.
The room does not verify the actor ids inside the block records (createdBy, contributors, lastChangedBy, read by attribution.block(id)): a modified client can write any actor id there. Display them as the client’s claim, or derive authorship from the client ids, whose bindings the room does verify.
Read-only sockets
When authorize returns access: 'read' (or readOnly: true), and for a comment socket:
- the client catches up with the document and receives live edits;
- it shares presence, so others see its caret;
- the room never asks it for its state. It sends the socket a read-only notice when it joins (the provider’s
readOnlyturnstrue, and itsaccessevent saysread), and drops every edit it sends with apermission-deniedreply (read-only). The socket stays open, and the provider emits'permission-denied'for each dropped edit, which forread-onlyis not a failure. The provider counts nothing as unsaved, so itssavedistrueonce it caught up.
Render read-only users with a read-only view. A readonly view connects to its room like an editable one, and the read-only socket keeps it a viewer whatever the page does:
<Edytor readonly server={serverUrl} room={documentId} {params} actor={{ id: userId }} />
What edytor does not do
Edytor ships no user accounts, sessions, sharing model or permission rules. authorize is where your application decides who may open which document and whether they may edit it; the room enforces that decision and nothing more.