Authoritative WebSocket relay server for @fieldnotes/sync.
The relay holds the canonical per-room canvas state and fans out element
operations to every other connection in the room. Clients connect, request a
snapshot to catch up, then stream upsert / remove / clear ops that the hub
applies and forwards.
SyncHub — transport-agnostic relay. Per-room canonical state lives behind
an async HubBackend; each room processes messages on its own serial queue so
concurrent edits to the same room never race, while different rooms run
independently.MemoryHubBackend — in-memory HubBackend (the default). It retains state for
abandoned rooms, and clear replaces elements with tombstones that are dropped only after
tombstoneRetentionMs — fine for dev / single-instance use. For a long-lived production
process, use RedisHubBackend with a key TTL, or roomIdleTimeoutMs.createSyncServer — a runnable ws reference server. Connect with
?room=<id> in the query string; a missing room closes the socket with WS code
4400.prepareAuthorityProposal — validates an admitted server actor and an authority:1
proposal into an immutable original request. The opt-in runtime then delegates atomic
acceptance to an application-provided driver.HubFanout — cross-instance live fan-out seam. SyncHub publishes each live
op to the fanout and forwards ops it receives from other instances to its local
connections. The default InMemoryHubFanout is in-process (a no-op for a single
instance). For multiple relay instances to share live ops, pass a shared fanout
via createSyncServer({ fanout }) (e.g. RedisHubFanout from
@fieldnotes/sync-redis) together with a shared backend — a
shared fanout alone leaves a new joiner's snapshot stale.HubFanout.publish() may return a promise. SyncHub writes an op to the backend first, then
publishes it, then delivers it to other local connections. If publication fails after the backend
write, the op is still delivered locally and handleMessage() rejects. Custom server integrations
must observe that rejection; createSyncServer reports it through its relay error path. The room
queue recovers so later messages can continue. Presence publication remains best-effort because
presence is ephemeral.
import { createSyncServer } from '@fieldnotes/sync-server';
const { close } = createSyncServer({ port: 8080 });
// ws://localhost:8080?room=my-room
Legacy rooms require protocol 3 and elementHierarchy: 1 before any snapshot, mutation, or
presence traffic. A substantive frame before capabilities, a missing or old marker, or a repeated
capability frame whose normalized content changes receives a best-effort unsupported response and
then closes with 4406. Authority admission sends an authority:1 upgrade-required frame before
the same close. Admission expires after 5 seconds. Authority capabilities use revision 2 with the
same hierarchy marker; native authority frames continue to use authority:1.
Version and tombstone behavior arrived with protocol 2 in 0.28.0. Protocol 3 adds the hierarchy
admission boundary. Every element carries a version and an optional editor, and the hub keeps
the newer write per element (higher version; on a tie, the editor that sorts later):
resolveAudience,
tombstone ownership check, authorize, plugins, version check, write, publish, deliver. On a
conflicting concurrent write the op restarts from the read, up to 3 attempts; then the sender
gets a correction.authorize configured, only the deleted element's owner, or the user who removed it, may
re-create a tombstoned id. Without authorize, ownership is not enforced.clear tombstones every element at its version + 1. Each recipient receives only the tombstones
whose stored audience it may read.editor: 'hub', and clears sent as from: 'hub', are dropped; only the
hub authors those.Tombstones are kept for 7 days by default. Set tombstoneRetentionMs on createSyncServer (for
the default backend) or on your backend's constructor; passing it together with backend throws.
createSyncServer({ port: 8080, tombstoneRetentionMs: 24 * 60 * 60 * 1000 });
HubBackend contractCustom backends implement an atomic compare-and-set:
interface HubBackend {
snapshot(room: string): Promise<{ elements: SyncElement[]; tombstones: StoredTombstone[] }>;
getRecord(room: string, id: string): Promise<HubRecord | undefined>; // element or tombstone
applyElement(
room: string,
write: ElementWrite, // upsert, remove (tombstone) or clear
expectedVersion: number | null, // null: no record may exist
): Promise<{ ok: true } | { ok: false; current: HubRecord | undefined }>;
// optional layer, service and evictRoom methods unchanged
}
applyElement writes only when the stored record's version equals expectedVersion; a clear
instead requires its expected map to match every stored element. Drop expired tombstones when
building a snapshot. get and apply are gone.
The hub advertises the opBatching capability and accepts batch frames from admitted protocol-3
clients. It runs each op of a batch in order through the same pipeline as a single op; a rejected op
gets its own correction and does not affect the others. Recipients that advertised opBatching get
the accepted ops as one batch, filtered for what each may read; others get individual ops. Fanout
to other instances stays one payload per op. A batch counts as one message for
messagesPerSecond and runs under one frame-policy deadline. Deploy every client and relay in a
room together for the protocol-3 hierarchy boundary.
The hub advertises opBatching only when a full batch fits its limits: maxMessageBytes ≥
SYNC_LIMITS.maxFrameBytes, maxJsonDepth ≥ SYNC_LIMITS.maxFrameJsonDepth and opBurst ≥
SYNC_LIMITS.maxBatchOps; below that, clients send single ops.
maxMessageBytes is a SyncHub option that createSyncServer passes for you; a direct SyncHub
adapter whose transport caps frames below 1 MiB must pass it, or the hub still advertises batching.
Each element op, single or batched, also counts against a per-connection op budget: opsPerSecond
(default 2,000) and opBurst (default 4,000), on both createSyncServer and SyncHub. Going over
closes the connection with 4408. Clients flush up to 20 times per second, so a drag of more than
about 100 elements needs a higher opsPerSecond.
Before the 4406 close for a rejected legacy capability frame, the hub sends an unsupported
reply explaining the refusal. Authority admission sends an authority:1 upgrade-required frame.
For the legacy reply, a frame policy waits up to 1 s before the close. Authority admission uses its
separate upgrade send and deadline.
Authority proposals whose element upsert is over AUTHORITY_ELEMENT_LIMITS are rejected.
prepareAuthorityProposal(actor, message) is a synchronous building block used by the
authoritative room runtime. Pass a server-supplied admitted actor and a raw client authority:1
proposal string. The actor must be an ordinary plain or null-prototype record with enumerable
own data properties. room must be an admitted room name; actorId is a required stable opaque
principal scope that the application must namespace consistently across instances and reconnects.
It must not fall back to a connection or display identity. Identity strings are limited to 1024
UTF-8 bytes. signal must be a native AbortSignal from the same Node realm.
The returned context copies only declared identity and lifecycle fields, snapshots and freezes
claims, retains the caller's live signal, and clamps deadlineAt to the earliest of the input
deadline, expiry, or five seconds from entry. The helper checks cancellation and the fixed
deadline again before returning. It installs no timer and cannot enforce a later driver commit
deadline. The proposal is the parsed and frozen original client request; its claimed owner
or audience fields remain untrusted. The configured driver must separately stamp authorized intents,
recheck current authority, ownership, generation, deadline and CAS at its atomic commit, and
persist dedupe under stable actor, room, generation and operation ID scope. An attempted commit
that times out may have an unknown outcome.
operationDigest is a server-only lowercase SHA-256 conflict key over the versioned domain,
JSON-encoded [room, actorId], and the canonical parsed proposal, separated by NUL bytes.
Equivalent JSON key order or whitespace produces the same digest across reconnects. The digest
is neither an authorization token nor proof of durable acceptance. Invalid input throws the
generic TypeError('Invalid authority proposal'); cancellation or an elapsed deadline throws
Error('Authority proposal expired').
createSyncServer({ authority }) selects a room before legacy admission, mutation, snapshot,
presence, plugin, backend or fanout handling. resolveRoom returning null keeps that room on
the existing legacy path. A non-null definition enables only authority:1 for that room;
incapable peers receive upgrade-required and close. The factory requires both authenticate
and framePolicy. Direct SyncHub.addConnection adapters cannot enable authority because the
runtime requires the factory's guarded, tracked send binding and lifetime signal.
The following is the host configuration shape. provisionedDriver must be a real implementation
of AuthorityDriver; the SDK deliberately does not provide production room storage. The
browser fixture below uses AuthorityFixtureDriver only for local acceptance.
import {
createSyncServer,
type AuthorityDriver,
type AuthorityRoomDefinition,
} from '@fieldnotes/sync-server';
declare const provisionedDriver: AuthorityDriver;
declare function myMembershipLookup(
req: unknown,
room: string,
): Promise<{ stableId: string; role: string } | null>;
declare function myFramePolicy(frame: unknown): Promise<boolean>;
const synthetic = {
requirement: {
key: 'synthetic',
pluginName: 'my-host',
version: 1,
validate: (data: unknown) => typeof data === 'string',
},
extensionKinds: ['synthetic-change'],
prepare: (mutation: { kind: string; payload?: unknown }) =>
mutation.kind === 'extension' && typeof mutation.payload === 'string' ? mutation.payload : null,
changes: (before: unknown, after: unknown) =>
before === after
? []
: [{ kind: 'extension' as const, extensionKind: 'synthetic-change', payload: after }],
};
const definition: AuthorityRoomDefinition = {
id: 'my-table-schema-v1',
extensions: [synthetic],
project: (context, state) => ({
...state,
elements: state.elements.filter(
(element) => element.audience !== 'private' || context.role === 'dm',
),
}),
canReadOwnerId: (context) => context.role === 'dm',
};
createSyncServer({
port: 8080,
authenticate: async ({ req, room }) => {
const member = await myMembershipLookup(req, room); // host-owned, current policy
return member ? { userId: member.stableId, role: member.role } : null;
},
framePolicy: { authorize: async (frame) => (await myFramePolicy(frame)) === true },
authority: {
driver: provisionedDriver,
resolveRoom: (room) => (room === 'table' ? definition : null),
resolveIdentity: (connection) => {
if (!connection.userId) throw new Error('stable identity required');
return { actorId: connection.userId, ownershipId: connection.userId };
},
},
});
The host must provision each room and unique generation outside the wire protocol; a missing
room does not auto-create. The driver must atomically check current room definition, generation,
read and write authorization, store-time deadline/expiry, ownership, audience, extension schema
and optional room CAS before applying a whole intent. Element owners are stamped from trusted
ownershipId and retained across removal and elements-only clear. Layers use version/editor LWW;
elements use commit order. Clear retains layers, extensions, ownership, dedupe, and generation.
Generation replacement, whole-room reset and external membership administration belong to the
host control plane. A trusted project function must return a subset of the captured image;
the runtime validates its shape, strips owner IDs for unprivileged readers, and sends only
their visible differences. Extension inventory (key, plugin, version and kinds) must match
exactly at negotiation and complete checkpoint assembly.
The driver's commit must persist state, a random opaque receipt, a separate random whole-room
CAS token, stable-actor dedupe record and immutable before/after publication evidence in one
transaction. A retained duplicate with the original digest returns its original receipt after
current read admission, even when CAS has moved. New IDs use the fn1: timestamp profile;
the driver checks store time, the 24-hour retry window and a persistent generation-scoped
eviction floor. An exception or timeout after invoking commit is an unknown outcome:
the caller keeps the original proposal and operation ID for retry. A definitive rejection says
only that this invocation did not mutate; retry-window-expired does not prove an earlier
uncertain attempt failed. A managed client must checkpoint and ask for explicit reconciliation
before reminting a separate logical operation.
readAfter returns linked opaque private positions; readEvidence leases immutable committed
images. Outbox claims/marking must recover globally without a connected peer and survive worker
crash. A metadata-to-evidence eviction returns typed history-unavailable; equal visible state
reconciles silently, while a real visible difference starts a complete checkpoint recovery.
Every driver read rechecks current authorization; capture leases are coherent and bounded. A
durable receipt proves commit, not delivery or client application. The author receives state
through the same ordered reader as other peers. A public cursor counts visible batches only;
private internal positions and hidden commits never enter public frames. Checkpoint completion
installs a new stream at revision zero, then reads changes committed during the stream.
The runtime caps 128 peers (32 prospective), 32 rooms, eight metadata tasks, two heavy workers, four prepared streams, 20 MiB complete state, and 1024 queued/active physical frames across authority factory connections (64 MiB total, with lower per-peer/room caps). The driver contract caps its publication metadata ring at 1024 records/8 MiB, separately from a 64 MiB immutable evidence arena per generation. Ownership retains at most 65,536 IDs/8 MiB, layers at most 4096 records/4 MiB, and successful dedupe at most 1024 records for up to 24 hours. Leases are store-time fenced, at most eight per room and 128 per driver, and last at most five seconds. One changes frame holds at most 1024 mutations/1 MiB; larger visible changes recover through a complete checkpoint. Physical frames are paced through guarded sends. These are application accounting bounds, not an RSS guarantee; full-state projection remains O(room size). The host driver must enforce its own transaction, evidence, lease, retirement and provisioning limits. The included fixture caps 64 live plus retiring generations; it is not Redis durability.
createManagedAuthorityConnection ships the managed authority client, including capability
negotiation, checkpoints, receipt barriers, and uncertain-outcome recovery. The authority runtime
and VTT authority extensions also ship. Authority presence, a production application
AuthorityDriver with Redis durability, administration, and RollKeeper adoption remain host-owned
or deferred.
For local synthetic inspection, see the authority browser fixture.
Trusted server integrations can broadcast ephemeral data without accessing the hub's connection registries:
const { hub } = createSyncServer({ port: 8080, fanout });
const localDeliveries = hub.broadcastPresence('my-room', {
kind: 'poke',
feature: 'initiative',
});
Recipients receive the existing presence envelope with the server-owned identity
{ from: 'hub', op: { kind: 'presence', data } }. The event is delivered to every local room
member and published to the configured HubFanout, so other relay instances deliver it to their
local members too. The return value counts frames accepted for sending on the originating hub only;
it is neither a completed physical delivery count nor a cluster-wide acknowledgement. An async
framePolicy can subsequently deny an accepted frame.
Server presence is best-effort, is not persisted, does not enter a room's durable operation queue,
and is not filtered by authorize or canRead. Validate and authorize application requests before
calling this trusted-host API. Data must be JSON-serializable; invalid data throws before delivery.
The method constructs the presence operation itself and does not accept a raw sync operation or
caller-controlled sender identity.
The server pings every client on an interval and terminates any that miss a pong,
so half-open sockets (a backgrounded iPad, dropped WiFi) are reaped instead of silently
leaking room membership. Configure via heartbeatIntervalMs (default 30000; 0
disables):
createSyncServer({ port: 8080, heartbeatIntervalMs: 30000 });
Browsers auto-pong at the protocol level, so no client change is needed.
close() stops accepting connections, closes active clients with code 1001, and waits up to
shutdownGraceMs (default 5000) before terminating clients that have not completed the close
handshake. Repeated calls return the same promise, so shutdown hooks can safely converge on it.
const server = createSyncServer({ port: 8080, shutdownGraceMs: 5000 });
await server.close();
The reference server bounds work and memory per connection by default. Oversized WebSocket messages
close with code 1009; message-rate, byte-rate, element-op and pending-auth queue violations close
with code 4408; a socket over the per-address or per-room connection cap closes with 4429.
Messages with excessive JSON nesting, and presence payloads over maxPresenceBytes, are dropped.
Presence sends immediately, then coalesces rapid updates so the latest state is forwarded at most
once per throttle interval.
createSyncServer({
port: 8080,
maxMessageBytes: 1024 * 1024,
maxJsonDepth: 32,
maxPendingAuthMessages: 100,
maxPendingAuthBytes: 2 * 1024 * 1024,
messagesPerSecond: 120,
messageBurst: 240,
bytesPerSecond: 4 * 1024 * 1024,
byteBurst: 8 * 1024 * 1024,
opsPerSecond: 2000,
opBurst: 4000,
presenceThrottleMs: 50,
maxPresenceBytes: 4 * 1024,
maxConnectionsPerIp: 64,
maxConnectionsPerRoom: 256,
clientAddress: (req) => req.socket.remoteAddress,
});
These values are the defaults. Tune them to the largest legitimate board operation and expected
client update rate. maxMessageBytes is enforced by the WebSocket parser before a complete message
is allocated, including fragmented messages. The pending-auth limits bound messages held while an
asynchronous authenticate hook is unresolved. Rate limits are per connection and use token
buckets: messageBurst / byteBurst are the short spike allowances and messagesPerSecond /
bytesPerSecond the refill rates, so relay amplification is bounded in bytes, not just frames.
Connection caps are taken at the upgrade, before authenticate runs, and count pending-auth
sockets; behind a trusted proxy supply clientAddress to read the forwarded address, and return
undefined to exempt a connection from the per-address cap. Rate and burst values must be positive
finite numbers; connection caps must be positive safe integers, or Infinity to disable a cap.
Invalid values throw during createSyncServer construction.
Pass framePolicy to opt admitted sockets into bounded transport. Its optional authorize hook
receives a frozen context for every valid inbound application frame and every final encoded outbound
application frame, including snapshots, capabilities, presence, corrections, plugin output, and
cross-instance fanout. The context contains the admitted connectionId, room, userId, role,
immutable authContext, optional expiresAt, direction, exact wire message, deadlineAt, and
an AbortSignal. An empty policy object enables the bounds without a hook. Authentication is
optional; anonymous sockets retain their admitted connection identity.
Guarded connections also expose optional Connection.sendAsync(message): Promise<void>.
It uses the same per-socket FIFO, authorization, and shared frame budgets as legacy
send(message): void. The promise resolves after the local WebSocket send callback succeeds;
it does not confirm peer receipt, application, a durable commit, or an entire checkpoint.
Callers must await or catch rejection. Failure rejects with a generic
Error('frame delivery failed') without exposing message, claims, policy, or socket errors.
The fixed five-second frame deadline, socket expiry, and disposal reject caller waits promptly.
If a guard or native callback remains hung, its active queue slot and budget reservation stay
occupied until that work actually settles. This deliberate bounded saturation prevents a failed
caller from admitting another physical write on the same lane. Canceled queued frames release
capacity immediately. Unguarded factory connections omit sendAsync; custom Connection
adapters may implement it. The authority runtime requires tracked guarded sends and awaits each
checkpoint frame or chunk before pulling the next. Existing send and
broadcastPresence keep their admission-only behavior; the presence count is not a delivery
acknowledgment.
createSyncServer({
port: 8080,
framePolicy: {
authorize: async ({ room, role, direction, message, signal }) => {
return myPolicy.canSendOrReceive({ room, role, direction, message, signal });
},
},
});
Only an exact true allows a frame. false closes that socket with 4403 (forbidden);
exceptions and nonboolean results close it with 1013 (resync required). Expiry closes with
4401 (unauthorized). Each frame has a five-second deadline, including queue wait, policy work,
processing, and the outbound ws.send callback. The fixed shared budget counts queued and active
inbound and outbound frames: 64 frames / 4 MiB per connection and 256 frames / 16 MiB per room.
Overflow closes the offending socket with 1013. Control ping, pong, and close frames bypass the
policy. No claims or lifecycle metadata are added to the wire envelope.
Direct SyncHub.handleMessage(connId, message, options?) callers may supply a trusted
MessageDispatchOptions with deadlineAt, signal, and beforeProcess. The caller schedules its
own timeout and abort. Queued cancellation resolves without processing; aborting active work is
cooperative and its promise settles only when the actual hook or operation settles. For guarded
plugin operations, ServerOpContext carries the same optional deadline and signal. Existing
two-argument hub calls retain their behavior. Already-running legacy backend/plugin work cannot be
rolled back by frame cancellation.
roomIdleTimeoutMs (off by default) frees per-room memory once a room has had no local connection
for that long: the hub's in-memory layer ledger, MemoryHubBackend data, and any server plugin
state through ServerSyncPlugin.evictRoom. With MemoryHubBackend this deletes the board, so set
it only where rooms are disposable or persisted elsewhere. For Redis use ttlSeconds on
RedisHubBackend instead.
The timeout must be a positive number of milliseconds up to 2 147 483 647 (about 24.8 days); larger values throw. Backends without layer methods keep layers in the hub's memory, so eviction forgets them too.
createSyncServer({ port: 8080, roomIdleTimeoutMs: 30 * 60 * 1000 });
The wire caps in SYNC_LIMITS (@fieldnotes/sync) apply to every frame the hub parses.
The current @fieldnotes/sync receive parser rejects frames nested deeper than 64. If you raise
maxJsonDepth above 62, deeply nested element data can be stored but not delivered, and a join
snapshot that contains it is dropped whole. Text and src caps count UTF-16 code units.
Pass an authenticate hook to gate connections:
import { createSyncServer } from '@fieldnotes/sync-server';
createSyncServer({
port: 8080,
authenticate: async ({ req, room }) => {
const token = new URL(req.url ?? '', 'http://x').searchParams.get('token');
const member = await myCampaign.verify(token, room); // your app's check (Redis/DB/JWT)
return member ? { userId: member.id, role: member.isDM ? 'dm' : 'player' } : null;
},
});
authenticate({ req, room }) → { userId, role? } | null runs on each connection and
may be sync or async. Returning null (or throwing) rejects the connection: the
socket is closed with WS code 4401 and the connection is never admitted to the room —
no membership, no snapshot. A resolved result admits the connection carrying its
userId and optional role.
The hook may also return authContext (JSON claims) and expiresAt (a positive safe integer
absolute Unix millisecond timestamp). The server copies and deeply freezes admitted claims;
later changes to the hook's object cannot change what plugins receive as
ServerOpContext.authContext. The claims and deadline are server-only and never enter sync
envelopes or presence. Invalid claims, invalid deadlines, and deadlines already reached at
admission close with 4401. Claims are limited to 16 KiB of UTF-8 JSON, 16 levels of nesting,
and 1024 visited entries. Getters, cycles, unsupported values and prototypes are rejected.
createSyncServer closes an idle socket when its deadline arrives and checks the deadline before
each inbound dispatch and outbound WebSocket send. The Node event loop must run before a timer can
close the socket. Work already dispatched or queued in the legacy room queue is not cancellable or
transactional; expiry prevents new dispatch and physical sends observed after the deadline, but
does not roll back earlier backend work. The authority driver contract requires atomic store-time
deadline enforcement at commit.
SyncHub.addConnection also copies and validates claims for direct callers, but custom transports
must enforce expiresAt themselves. Received cross-instance fanout has no authenticated claims:
its payload and from field do not create a ServerOpContext.authContext.
With no hook, rooms stay open: every connection is admitted anonymously with
userId = connId. role is captured and passed to the authorize and
canRead hooks (see Read filtering). Nothing enforces it unless a hook is
configured.
Messages that arrive during an async auth (notably the client's initial
request-snapshot) are queued and replayed once the connection is admitted, so the
first snapshot is never lost to the auth round-trip.
The relay assigns every admitted socket an opaque connection identity. That server-owned identity
is used as from on all relayed mutations, presence updates, cross-instance fan-out, and disconnect
leave events; the client-controlled envelope from cannot impersonate another connection. Presence
identity is intentionally connection-scoped and changes after reconnecting. Application authorization
continues to use the authenticated userId and role, not this transport identity.
authenticate receives token, resolved by the exported readBearerToken(req) in this order:
A Sec-WebSocket-Protocol entry fieldnotes-bearer.<token> — the browser-safe channel. A
browser WebSocket can't set request headers, but it can offer subprotocols; the relay reads
the token, selects the fieldnotes-sync subprotocol and never echoes the bearer entry. On the
client, bearerSubprotocols(token) from @fieldnotes/sync builds the offer:
import {
WebSocketTransport,
bearerSubprotocols,
createManagedSyncConnection,
} from '@fieldnotes/sync';
new WebSocketTransport('wss://relay?room=R', { protocols: bearerSubprotocols(token) });
// or, managed:
createManagedSyncConnection({
store,
clientId,
resolveUrl: async () => ({
url: 'wss://relay?room=R',
protocols: bearerSubprotocols(await mint()),
}),
});
The token must be a valid subprotocol token (JWT and base64url alphabets qualify; base64 =
padding does not).
An Authorization: Bearer <token> header, for non-browser clients.
The token URL query parameter (ws://relay?room=R&token=…). Still supported so existing
clients keep working, but URLs land in access/proxy logs: prefer the channels above, and use
short-lived / single-use tokens if you must stay on the URL.
req is still passed, so an authenticate hook that reads req.url or req.headers itself
keeps working unchanged.
Pass an authorize hook to gate writes. The hub calls it before applying each data
op (upsert / remove / clear) and drops denied ops — a denied op is not applied
to room state and not forwarded to any other connection:
authorize(ctx) => boolean | Promise<boolean>
ctx is an AuthorizeContext:
{
userId?: string; // the connection's authenticated user (from authenticate)
role?: string; // the connection's role (from authenticate)
room: string;
op: SyncOp; // the incoming upsert / remove / clear
currentElement?: OwnedElement; // the STORED element, if this id already exists
}
currentElement is the element currently in room state for an upsert/remove of an
existing id (typed OwnedElement = SyncElement), and
undefined for a new, absent or deleted (tombstoned) id.
Ownership is server-stamped and un-forgeable. A new element's ownerId is set to the
authenticated creator; on edit the stored owner is preserved; a client-supplied
ownerId is always discarded. A policy can therefore trust currentElement.ownerId
to enforce "own elements only".
ownerId stays on the server. It is stripped from every outbound frame (live ops,
snapshots, corrections) so a viewer's save file never records who
created what. Pass canReadOwnerId({ userId, role, room }) => boolean to reveal it to
privileged viewers, e.g. canReadOwnerId: ({ role }) => role === 'dm'.
With no hook, rooms are OPEN (allow-all — every op is accepted).
When canRead filtering is in use, op.element.audience is what the sender asserted unless a
resolveAudience hook is configured (see Read filtering); an authorize policy
without that hook must validate the audience itself.
A copy-paste DM / player / display policy:
createSyncServer({
port: 8080,
authenticate: /* … supplies userId + role … */,
authorize: ({ role, op, currentElement, userId }) => {
if (role === 'dm') return true;
if (role === 'display') return false; // read-only monitor
if (role === 'player') { // own elements only, never destructive
if (op.kind === 'clear') return false;
if (op.kind === 'upsert') return !currentElement || currentElement.ownerId === userId;
if (op.kind === 'remove') return currentElement?.ownerId === userId;
return false;
}
return false;
},
});
Important:
authenticate to supply a STABLE userId. The
no-hook anonymous default is userId = connId, which changes on every reconnect — a
user would lose access to their own elements after reconnecting. createSyncServer
therefore throws when authorize is configured without authenticate.backend.getRecord, one or two Redis HGETs) once per
compare-and-set attempt (up to 3) before it is authorized, whether or not authorize is configured.canRead (see
Read filtering). authorize gates writes only.authorize denies an op, the hub sends the offending client a corrective op so its
optimistic local edit self-corrects immediately — no client change, no waiting for reconnect:
a rejected new element is removed, a rejected edit/remove is re-upserted from the canonical
stored element, and a rejected clear gets a fresh snapshot. The correction reuses existing op
kinds and is sent only to the offending connection. When canRead is configured, corrections use
the same viewer filter: unreadable canonical upserts become byte-free removes and corrective
snapshots omit unreadable elements.Pass a canRead hook to gate reads — what each viewer receives. Unlike client-side
hiding, the hub filters ops before they leave the server, so hidden elements never reach an
unauthorized client on either path: the live broadcast and the snapshot a client gets on join.
canRead({ userId, role, room, audience }) => boolean
audience is the opaque tag the client stamps on its own outgoing upserts via @fieldnotes/sync's
resolveAudience (e.g. 'dm' / 'shared', derived from the app's layers). With no hook,
everyone sees everything.
A two-tier DM / player policy — the relay's canRead paired with the client's resolveAudience:
// relay
createSyncServer({
port: 8080,
authenticate: /* … supplies userId + role … */,
canRead: ({ role, audience }) => audience !== 'dm' || role === 'dm',
});
// client (@fieldnotes/sync)
new SyncClient({ store, transport, resolveAudience: (el) => layerOf(el) }); // → 'dm' | 'shared'
Moving an element between audiences re-evaluates visibility per viewer: a viewer who loses access gets a synthetic remove, one who gains it gets an add.
Preconditions:
userId/role from authenticate; the
no-hook anonymous default is per-connection (userId = connId) and changes on reconnect.canRead on every instance. Unlike authorize (which runs on the write's origin
instance only), canRead runs on every instance — each re-filters fanned-out ops for its own
local members — so all relay instances must inject the same canRead, alongside the existing
shared-backend + shared-fanout requirement.audience arrives client-asserted. Without a resolveAudience hook a
player can tag an upsert dm to hide it from the table, or retag a hidden element shared to
reveal it, so one of the two following hooks is required for read secrecy:
resolveAudience({ userId, role, room, element, currentElement }) => string | undefined
(recommended) makes the hub the authority: its return value replaces the client's tag
(undefined clears it) before authorize, storage and relay. A policy such as
({ role, currentElement }) => currentElement?.audience ?? (role === 'dm' ? 'dm' : 'shared')
keeps an element's audience stable and lets only a DM create hidden content.authorize must enforce the audience contract itself: reject an upsert whose
op.element.audience the sender may not write to, and reject one whose audience differs from
currentElement.audience unless the sender may move it.A Redis HubBackend and cross-instance fan-out ship in @fieldnotes/sync-redis.
An AuthorityExtension may explicitly own fog-meta and fog-patch through legacyKinds.
Ownership is opt-in, immutable after room admission, included in exact capability negotiation, and
cannot overlap another extension or a generic kind. Unowned, malformed, oversized, throwing, or
foreign fog proposals fail before driver invocation; projected changes are accepted only from the
extension that owns that exact legacy kind. This does not activate a legacy VTT plugin or backend.
SyncHubOptions.plugins installs ordered ServerSyncPlugin middleware. Plugins can register
codec-validated extension kinds, provide versioned snapshots, return sender-only corrections, and
choose local or shared fanout per accepted operation. The hub writes before it publishes, and
process may run up to 3 times for one op when a concurrent write conflicts, so keep side effects
in broadcast and corrections. Fog authorization and state application are
supplied by createFogServerPlugin() from @fieldnotes/vtt/server; the generic server has no
runtime VTT dependency.
From an installed workspace, pack the server into a release directory:
pnpm --filter @fieldnotes/sync-server pack --pack-destination <directory>
The prepack script rebuilds core, sync, then the server. Inspect each current archive's runtime
files and type declarations. With owner approval, publish the coordinated releases in dependency
order: core 0.100.0, sync 0.30.0, sync-server 0.30.0, then sync-redis 0.15.0. Packing verifies an
archive locally; it does not publish or establish registry availability.