@fieldnotes/sync-server 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -34,4 +34,108 @@ const { close } = createSyncServer({ port: 8080 });
34
34
  // ws://localhost:8080?room=my-room
35
35
  ```
36
36
 
37
- Auth and a Redis `HubBackend` are upcoming.
37
+ ## Authentication
38
+
39
+ Pass an `authenticate` hook to gate connections:
40
+
41
+ ```ts
42
+ import { createSyncServer } from '@fieldnotes/sync-server';
43
+
44
+ createSyncServer({
45
+ port: 8080,
46
+ authenticate: async ({ req, room }) => {
47
+ const token = new URL(req.url ?? '', 'http://x').searchParams.get('token');
48
+ const member = await myCampaign.verify(token, room); // your app's check (Redis/DB/JWT)
49
+ return member ? { userId: member.id, role: member.isDM ? 'dm' : 'player' } : null;
50
+ },
51
+ });
52
+ ```
53
+
54
+ `authenticate({ req, room }) → { userId, role? } | null` runs on each connection and
55
+ may be sync or async. Returning `null` (or throwing) **rejects** the connection: the
56
+ socket is closed with WS code `4401` and the connection is never admitted to the room —
57
+ no membership, no snapshot. A resolved result admits the connection carrying its
58
+ `userId` and optional `role`.
59
+
60
+ With **no hook**, rooms stay open: every connection is admitted anonymously with
61
+ `userId = connId`. `role` is captured now and enforced in an upcoming release
62
+ (role-based authorization and per-viewer visibility filtering).
63
+
64
+ Messages that arrive during an async auth (notably the client's initial
65
+ `request-snapshot`) are queued and replayed once the connection is admitted, so the
66
+ first snapshot is never lost to the auth round-trip.
67
+
68
+ ### Passing a token
69
+
70
+ A browser `WebSocket` can't set request headers, so pass the token as a URL query
71
+ param (`ws://relay?room=R&token=…`) and read it from `req.url` in `authenticate`. URLs
72
+ land in access/proxy logs, so prefer **short-lived / single-use** tokens. Non-browser
73
+ clients can instead put the token in `req.headers` (e.g. `Authorization`), which
74
+ `authenticate` reads directly.
75
+
76
+ ## Authorization
77
+
78
+ Pass an `authorize` hook to gate **writes**. The hub calls it before applying each data
79
+ op (`upsert` / `remove` / `clear`) and **drops denied ops** — a denied op is not applied
80
+ to room state and not forwarded to any other connection:
81
+
82
+ ```ts
83
+ authorize(ctx) => boolean | Promise<boolean>
84
+ ```
85
+
86
+ `ctx` is an `AuthorizeContext`:
87
+
88
+ ```ts
89
+ {
90
+ userId?: string; // the connection's authenticated user (from authenticate)
91
+ role?: string; // the connection's role (from authenticate)
92
+ room: string;
93
+ op: SyncOp; // the incoming upsert / remove / clear
94
+ currentElement?: OwnedElement; // the STORED element, if this id already exists
95
+ }
96
+ ```
97
+
98
+ `currentElement` is the element currently in room state for an `upsert`/`remove` of an
99
+ **existing** id (typed `OwnedElement = CanvasElement & { ownerId?: string }`), and
100
+ `undefined` for a new/absent id.
101
+
102
+ **Ownership is server-stamped and un-forgeable.** A new element's `ownerId` is set to the
103
+ authenticated creator; on edit the stored owner is **preserved**; a client-supplied
104
+ `ownerId` is always **discarded**. A policy can therefore trust `currentElement.ownerId`
105
+ to enforce "own elements only".
106
+
107
+ With **no hook**, rooms are OPEN (allow-all — every op is accepted).
108
+
109
+ A copy-paste DM / player / display policy:
110
+
111
+ ```ts
112
+ createSyncServer({
113
+ port: 8080,
114
+ authenticate: /* … supplies userId + role … */,
115
+ authorize: ({ role, op, currentElement, userId }) => {
116
+ if (role === 'dm') return true;
117
+ if (role === 'display') return false; // read-only monitor
118
+ if (role === 'player') { // own elements only, never destructive
119
+ if (op.kind === 'clear') return false;
120
+ if (op.kind === 'upsert') return !currentElement || currentElement.ownerId === userId;
121
+ if (op.kind === 'remove') return currentElement?.ownerId === userId;
122
+ return false;
123
+ }
124
+ return false;
125
+ },
126
+ });
127
+ ```
128
+
129
+ **Important:**
130
+
131
+ - Ownership-based authz **requires `authenticate` to supply a STABLE `userId`**. The
132
+ no-hook anonymous default is `userId = connId`, which changes on every reconnect — a
133
+ user would lose access to their own elements after reconnecting.
134
+ - The authz path adds one `backend.get` (a Redis `HGET`) per data op — negligible for
135
+ low-write use.
136
+ - Reads / visibility (a player not **receiving** hidden content) are a separate, upcoming
137
+ concern (D3). `authorize` gates writes only.
138
+ - Denied ops are dropped **silently** — the client's optimistic local edit self-corrects
139
+ on its next reconnect/resync.
140
+
141
+ A Redis `HubBackend` and cross-instance fan-out ship in [`@fieldnotes/sync-redis`](../sync-redis).
package/dist/index.cjs CHANGED
@@ -45,6 +45,9 @@ var MemoryHubBackend = class {
45
45
  async snapshot(room) {
46
46
  return [...this.room(room).values()];
47
47
  }
48
+ async get(room, id) {
49
+ return this.room(room).get(id);
50
+ }
48
51
  async apply(room, op) {
49
52
  (0, import_sync.applyOpToMap)(this.room(room), op);
50
53
  }
@@ -84,10 +87,12 @@ var SyncHub = class {
84
87
  instanceId;
85
88
  fanout;
86
89
  fanoutUnsub;
90
+ authorize;
87
91
  constructor(options = {}) {
88
92
  this.backend = options.backend ?? new MemoryHubBackend();
89
93
  this.instanceId = options.instanceId ?? generateInstanceId();
90
94
  this.fanout = options.fanout ?? new InMemoryHubFanout();
95
+ this.authorize = options.authorize;
91
96
  this.fanoutUnsub = this.fanout.subscribe((payload) => this.onFanout(payload));
92
97
  }
93
98
  addConnection(conn) {
@@ -135,15 +140,37 @@ var SyncHub = class {
135
140
  JSON.stringify({ from: HUB_FROM, op: { kind: "snapshot", to: env.from, elements } })
136
141
  );
137
142
  } else if (op.kind === "upsert" || op.kind === "remove" || op.kind === "clear") {
138
- await this.backend.apply(conn.room, op);
143
+ let outboundOp = op;
144
+ let outboundMessage = message;
145
+ if (this.authorize) {
146
+ const id = op.kind === "upsert" ? op.element.id : op.kind === "remove" ? op.id : void 0;
147
+ const current = id !== void 0 ? await this.backend.get(conn.room, id) : void 0;
148
+ const allowed = await this.authorize({
149
+ userId: conn.userId,
150
+ role: conn.role,
151
+ room: conn.room,
152
+ op,
153
+ currentElement: current
154
+ });
155
+ if (!allowed) return;
156
+ if (op.kind === "upsert") {
157
+ const ownerId = current?.ownerId ?? conn.userId;
158
+ const stampedElement = { ...op.element, ownerId };
159
+ outboundOp = { kind: "upsert", element: stampedElement };
160
+ outboundMessage = JSON.stringify({ from: env.from, op: outboundOp });
161
+ }
162
+ }
163
+ await this.backend.apply(conn.room, outboundOp);
139
164
  const members = this.rooms.get(conn.room);
140
165
  if (members) {
141
166
  for (const id of members) {
142
167
  if (id === conn.id) continue;
143
- this.conns.get(id)?.send(message);
168
+ this.conns.get(id)?.send(outboundMessage);
144
169
  }
145
170
  }
146
- this.fanout.publish(JSON.stringify({ o: this.instanceId, room: conn.room, m: message }));
171
+ this.fanout.publish(
172
+ JSON.stringify({ o: this.instanceId, room: conn.room, m: outboundMessage })
173
+ );
147
174
  }
148
175
  }
149
176
  onFanout(payload) {
@@ -177,7 +204,8 @@ function createSyncServer(options = {}) {
177
204
  const hub = new SyncHub({
178
205
  backend: options.backend,
179
206
  fanout: options.fanout,
180
- instanceId: options.instanceId
207
+ instanceId: options.instanceId,
208
+ authorize: options.authorize
181
209
  });
182
210
  const wss = options.server ? new import_ws.WebSocketServer({ server: options.server }) : new import_ws.WebSocketServer({ port: options.port ?? 0 });
183
211
  let counter = 0;
@@ -189,20 +217,48 @@ function createSyncServer(options = {}) {
189
217
  return;
190
218
  }
191
219
  const connId = `c${++counter}-${Math.random().toString(36).slice(2, 8)}`;
192
- hub.addConnection({
193
- id: connId,
194
- room,
195
- send: (m) => {
196
- try {
197
- ws.send(m);
198
- } catch {
199
- }
220
+ let state = "pending";
221
+ let closed = false;
222
+ const queue = [];
223
+ const MAX_QUEUE = 100;
224
+ const send = (m) => {
225
+ try {
226
+ ws.send(m);
227
+ } catch {
200
228
  }
201
- });
229
+ };
202
230
  ws.on("message", (data) => {
203
- void hub.handleMessage(connId, String(data)).catch((err) => console.error("[sync-server]", err));
231
+ const msg = String(data);
232
+ if (state === "rejected") return;
233
+ if (state === "pending") {
234
+ if (queue.length < MAX_QUEUE) queue.push(msg);
235
+ return;
236
+ }
237
+ void hub.handleMessage(connId, msg).catch((err) => console.error("[sync-server]", err));
238
+ });
239
+ ws.on("close", () => {
240
+ closed = true;
241
+ if (state === "ready") hub.removeConnection(connId);
242
+ });
243
+ Promise.resolve(options.authenticate ? options.authenticate({ req, room }) : { userId: connId }).then((result) => {
244
+ if (closed) return;
245
+ if (!result) {
246
+ state = "rejected";
247
+ ws.close(4401, "unauthorized");
248
+ return;
249
+ }
250
+ state = "ready";
251
+ hub.addConnection({ id: connId, room, userId: result.userId, role: result.role, send });
252
+ for (const m of queue) {
253
+ void hub.handleMessage(connId, m).catch((err) => console.error("[sync-server]", err));
254
+ }
255
+ queue.length = 0;
256
+ }).catch(() => {
257
+ if (!closed) {
258
+ state = "rejected";
259
+ ws.close(4401, "unauthorized");
260
+ }
204
261
  });
205
- ws.on("close", () => hub.removeConnection(connId));
206
262
  });
207
263
  return {
208
264
  hub,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/sync-hub.ts","../src/memory-hub-backend.ts","../src/hub-fanout.ts","../src/create-sync-server.ts"],"sourcesContent":["export { SyncHub } from './sync-hub';\nexport type { SyncHubOptions, Connection } from './sync-hub';\nexport { MemoryHubBackend } from './memory-hub-backend';\nexport type { HubBackend } from './hub-backend';\nexport { createSyncServer } from './create-sync-server';\nexport type { CreateSyncServerOptions } from './create-sync-server';\nexport { InMemoryHubFanout } from './hub-fanout';\nexport type { HubFanout } from './hub-fanout';\n","import { parseEnvelope } from '@fieldnotes/sync';\nimport { MemoryHubBackend } from './memory-hub-backend';\nimport { InMemoryHubFanout, type HubFanout } from './hub-fanout';\nimport type { HubBackend } from './hub-backend';\n\nexport interface Connection {\n id: string;\n room: string;\n send(message: string): void;\n}\n\nexport interface SyncHubOptions {\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n}\n\nconst HUB_FROM = 'hub';\n\nfunction generateInstanceId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')\n return crypto.randomUUID();\n return `i-${Math.random().toString(36).slice(2)}`;\n}\n\nexport class SyncHub {\n private readonly backend: HubBackend;\n private readonly conns = new Map<string, Connection>();\n private readonly rooms = new Map<string, Set<string>>(); // room → connIds\n private readonly roomQueues = new Map<string, Promise<void>>(); // room → serial tail\n private readonly instanceId: string;\n private readonly fanout: HubFanout;\n private readonly fanoutUnsub: () => void;\n\n constructor(options: SyncHubOptions = {}) {\n this.backend = options.backend ?? new MemoryHubBackend();\n this.instanceId = options.instanceId ?? generateInstanceId();\n this.fanout = options.fanout ?? new InMemoryHubFanout();\n this.fanoutUnsub = this.fanout.subscribe((payload) => this.onFanout(payload));\n }\n\n addConnection(conn: Connection): void {\n this.conns.set(conn.id, conn);\n let set = this.rooms.get(conn.room);\n if (!set) {\n set = new Set();\n this.rooms.set(conn.room, set);\n }\n set.add(conn.id);\n }\n\n removeConnection(connId: string): void {\n const conn = this.conns.get(connId);\n if (!conn) return;\n this.conns.delete(connId);\n const members = this.rooms.get(conn.room);\n if (members) {\n members.delete(connId);\n if (members.size === 0) {\n this.rooms.delete(conn.room);\n this.roomQueues.delete(conn.room);\n }\n }\n }\n\n roomCount(): number {\n return this.rooms.size;\n }\n\n handleMessage(connId: string, message: string): Promise<void> {\n const conn = this.conns.get(connId);\n if (!conn) return Promise.resolve();\n const room = conn.room;\n const prev = this.roomQueues.get(room) ?? Promise.resolve();\n const next = prev\n .then(() => this.process(conn, message))\n .catch(() => {\n // swallow so one failed message never wedges the room's serial queue\n });\n this.roomQueues.set(room, next);\n return next;\n }\n\n private async process(conn: Connection, message: string): Promise<void> {\n const env = parseEnvelope(message);\n if (!env) return;\n const op = env.op;\n if (op.kind === 'request-snapshot') {\n const elements = await this.backend.snapshot(conn.room);\n conn.send(\n JSON.stringify({ from: HUB_FROM, op: { kind: 'snapshot', to: env.from, elements } }),\n );\n } else if (op.kind === 'upsert' || op.kind === 'remove' || op.kind === 'clear') {\n await this.backend.apply(conn.room, op);\n const members = this.rooms.get(conn.room);\n if (members) {\n for (const id of members) {\n if (id === conn.id) continue;\n this.conns.get(id)?.send(message);\n }\n }\n this.fanout.publish(JSON.stringify({ o: this.instanceId, room: conn.room, m: message }));\n }\n // 'snapshot' from a client → ignored\n }\n\n private onFanout(payload: string): void {\n // Off the serial queue on purpose: forward-only (no backend re-apply — the origin already applied to the\n // SHARED backend), and delivery is already ordered. Do not wrap this in roomQueues.\n let env: { o?: unknown; room?: unknown; m?: unknown };\n try {\n env = JSON.parse(payload);\n } catch {\n return;\n }\n if (typeof env.o !== 'string' || typeof env.room !== 'string' || typeof env.m !== 'string')\n return;\n if (env.o === this.instanceId) return; // our own publish — already forwarded locally\n const members = this.rooms.get(env.room);\n if (!members) return;\n const m = env.m;\n for (const id of members) {\n try {\n this.conns.get(id)?.send(m);\n } catch {\n /* a throwing socket must not break the fanout loop */\n }\n }\n }\n\n close(): void {\n this.fanoutUnsub();\n }\n}\n","import { applyOpToMap, type SyncOp } from '@fieldnotes/sync';\r\nimport type { CanvasElement } from '@fieldnotes/core';\r\nimport type { HubBackend } from './hub-backend';\r\n\r\nexport class MemoryHubBackend implements HubBackend {\r\n private rooms = new Map<string, Map<string, CanvasElement>>();\r\n\r\n private room(id: string): Map<string, CanvasElement> {\r\n let r = this.rooms.get(id);\r\n if (!r) {\r\n r = new Map();\r\n this.rooms.set(id, r);\r\n }\r\n return r;\r\n }\r\n\r\n async snapshot(room: string): Promise<CanvasElement[]> {\r\n return [...this.room(room).values()];\r\n }\r\n\r\n async apply(room: string, op: SyncOp): Promise<void> {\r\n applyOpToMap(this.room(room), op);\r\n }\r\n}\r\n","export interface HubFanout {\n publish(payload: string): void;\n subscribe(handler: (payload: string) => void): () => void;\n close?(): void;\n}\n\nexport class InMemoryHubFanout implements HubFanout {\n private readonly handlers = new Set<(payload: string) => void>();\n\n publish(payload: string): void {\n for (const h of this.handlers) {\n try {\n h(payload);\n } catch {\n /* one throwing subscriber must not break the publish loop */\n }\n }\n }\n\n subscribe(handler: (payload: string) => void): () => void {\n this.handlers.add(handler);\n return () => this.handlers.delete(handler);\n }\n}\n","import { WebSocketServer } from 'ws';\nimport type { Server } from 'http';\nimport { SyncHub } from './sync-hub';\nimport type { HubBackend } from './hub-backend';\nimport type { HubFanout } from './hub-fanout';\n\nexport interface CreateSyncServerOptions {\n port?: number;\n server?: Server;\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n}\n\nexport function createSyncServer(options: CreateSyncServerOptions = {}): {\n hub: SyncHub;\n wss: WebSocketServer;\n close: () => Promise<void>;\n} {\n const hub = new SyncHub({\n backend: options.backend,\n fanout: options.fanout,\n instanceId: options.instanceId,\n });\n const wss = options.server\n ? new WebSocketServer({ server: options.server })\n : new WebSocketServer({ port: options.port ?? 0 });\n let counter = 0;\n wss.on('connection', (ws, req) => {\n const url = new URL(req.url ?? '', 'http://localhost');\n const room = url.searchParams.get('room');\n if (!room) {\n ws.close(1008, 'room required');\n return;\n }\n const connId = `c${++counter}-${Math.random().toString(36).slice(2, 8)}`;\n hub.addConnection({\n id: connId,\n room,\n send: (m) => {\n try {\n ws.send(m);\n } catch {\n /* socket closed mid-send */\n }\n },\n });\n ws.on('message', (data) => {\n void hub\n .handleMessage(connId, String(data))\n .catch((err) => console.error('[sync-server]', err));\n });\n ws.on('close', () => hub.removeConnection(connId));\n });\n return {\n hub,\n wss,\n close: () =>\n new Promise<void>((resolve) => {\n hub.close();\n wss.close(() => resolve());\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,eAA8B;;;ACA9B,kBAA0C;AAInC,IAAM,mBAAN,MAA6C;AAAA,EAC1C,QAAQ,oBAAI,IAAwC;AAAA,EAEpD,KAAK,IAAwC;AACnD,QAAI,IAAI,KAAK,MAAM,IAAI,EAAE;AACzB,QAAI,CAAC,GAAG;AACN,UAAI,oBAAI,IAAI;AACZ,WAAK,MAAM,IAAI,IAAI,CAAC;AAAA,IACtB;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,SAAS,MAAwC;AACrD,WAAO,CAAC,G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0BAAgB,EAAE,MAAM,QAAQ,QAAQ,EAAE,CAAC;AACnD,MAAI,UAAU;AACd,MAAI,GAAG,cAAc,CAAC,IAAI,QAAQ;AAChC,UAAM,MAAM,IAAI,IAAI,IAAI,OAAO,IAAI,kBAAkB;AACrD,UAAM,OAAO,IAAI,aAAa,IAAI,MAAM;AACxC,QAAI,CAAC,MAAM;AACT,SAAG,MAAM,MAAM,eAAe;AAC9B;AAAA,IACF;AACA,UAAM,SAAS,IAAI,EAAE,OAAO,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AACtE,QAAI,cAAc;AAAA,MAChB,IAAI;AAAA,MACJ;AAAA,MACA,MAAM,CAAC,MAAM;AACX,YAAI;AACF,aAAG,KAAK,CAAC;AAAA,QACX,QAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF,CAAC;AACD,OAAG,GAAG,WAAW,CAAC,SAAS;AACzB,WAAK,IACF,cAAc,QAAQ,OAAO,IAAI,CAAC,EAClC,MAAM,CAAC,QAAQ,QAAQ,MAAM,iBAAiB,GAAG,CAAC;AAAA,IACvD,CAAC;AACD,OAAG,GAAG,SAAS,MAAM,IAAI,iBAAiB,MAAM,CAAC;AAAA,EACnD,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MACL,IAAI,QAAc,CAAC,YAAY;AAC7B,UAAI,MAAM;AACV,UAAI,MAAM,MAAM,QAAQ,CAAC;AAAA,IAC3B,CAAC;AAAA,EACL;AACF;","names":["import_sync"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/sync-hub.ts","../src/memory-hub-backend.ts","../src/hub-fanout.ts","../src/create-sync-server.ts"],"sourcesContent":["export { SyncHub } from './sync-hub';\nexport type { SyncHubOptions, Connection } from './sync-hub';\nexport { MemoryHubBackend } from './memory-hub-backend';\nexport type { HubBackend } from './hub-backend';\nexport { createSyncServer } from './create-sync-server';\nexport type { CreateSyncServerOptions } from './create-sync-server';\nexport { InMemoryHubFanout } from './hub-fanout';\nexport type { HubFanout } from './hub-fanout';\nexport type { AuthInfo, AuthResult, Authenticate } from './authenticate';\nexport type { Authorize, AuthorizeContext, OwnedElement } from './authorize';\n","import { parseEnvelope, type SyncOp } from '@fieldnotes/sync';\nimport { MemoryHubBackend } from './memory-hub-backend';\nimport { InMemoryHubFanout, type HubFanout } from './hub-fanout';\nimport type { HubBackend } from './hub-backend';\nimport type { Authorize, OwnedElement } from './authorize';\n\nexport interface Connection {\n id: string;\n room: string;\n userId?: string;\n role?: string;\n send(message: string): void;\n}\n\nexport interface SyncHubOptions {\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n authorize?: Authorize;\n}\n\nconst HUB_FROM = 'hub';\n\nfunction generateInstanceId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')\n return crypto.randomUUID();\n return `i-${Math.random().toString(36).slice(2)}`;\n}\n\nexport class SyncHub {\n private readonly backend: HubBackend;\n private readonly conns = new Map<string, Connection>();\n private readonly rooms = new Map<string, Set<string>>(); // room → connIds\n private readonly roomQueues = new Map<string, Promise<void>>(); // room → serial tail\n private readonly instanceId: string;\n private readonly fanout: HubFanout;\n private readonly fanoutUnsub: () => void;\n private readonly authorize?: Authorize;\n\n constructor(options: SyncHubOptions = {}) {\n this.backend = options.backend ?? new MemoryHubBackend();\n this.instanceId = options.instanceId ?? generateInstanceId();\n this.fanout = options.fanout ?? new InMemoryHubFanout();\n this.authorize = options.authorize;\n this.fanoutUnsub = this.fanout.subscribe((payload) => this.onFanout(payload));\n }\n\n addConnection(conn: Connection): void {\n this.conns.set(conn.id, conn);\n let set = this.rooms.get(conn.room);\n if (!set) {\n set = new Set();\n this.rooms.set(conn.room, set);\n }\n set.add(conn.id);\n }\n\n removeConnection(connId: string): void {\n const conn = this.conns.get(connId);\n if (!conn) return;\n this.conns.delete(connId);\n const members = this.rooms.get(conn.room);\n if (members) {\n members.delete(connId);\n if (members.size === 0) {\n this.rooms.delete(conn.room);\n this.roomQueues.delete(conn.room);\n }\n }\n }\n\n roomCount(): number {\n return this.rooms.size;\n }\n\n handleMessage(connId: string, message: string): Promise<void> {\n const conn = this.conns.get(connId);\n if (!conn) return Promise.resolve();\n const room = conn.room;\n const prev = this.roomQueues.get(room) ?? Promise.resolve();\n const next = prev\n .then(() => this.process(conn, message))\n .catch(() => {\n // swallow so one failed message never wedges the room's serial queue\n });\n this.roomQueues.set(room, next);\n return next;\n }\n\n private async process(conn: Connection, message: string): Promise<void> {\n const env = parseEnvelope(message);\n if (!env) return;\n const op = env.op;\n if (op.kind === 'request-snapshot') {\n const elements = await this.backend.snapshot(conn.room);\n conn.send(\n JSON.stringify({ from: HUB_FROM, op: { kind: 'snapshot', to: env.from, elements } }),\n );\n } else if (op.kind === 'upsert' || op.kind === 'remove' || op.kind === 'clear') {\n let outboundOp: SyncOp = op;\n let outboundMessage = message;\n if (this.authorize) {\n const id = op.kind === 'upsert' ? op.element.id : op.kind === 'remove' ? op.id : undefined;\n const current: OwnedElement | undefined =\n id !== undefined ? await this.backend.get(conn.room, id) : undefined;\n const allowed = await this.authorize({\n userId: conn.userId,\n role: conn.role,\n room: conn.room,\n op,\n currentElement: current,\n });\n if (!allowed) return;\n if (op.kind === 'upsert') {\n const ownerId = current?.ownerId ?? conn.userId;\n const stampedElement: OwnedElement = { ...op.element, ownerId };\n outboundOp = { kind: 'upsert', element: stampedElement };\n outboundMessage = JSON.stringify({ from: env.from, op: outboundOp });\n }\n }\n await this.backend.apply(conn.room, outboundOp);\n const members = this.rooms.get(conn.room);\n if (members) {\n for (const id of members) {\n if (id === conn.id) continue;\n this.conns.get(id)?.send(outboundMessage);\n }\n }\n this.fanout.publish(\n JSON.stringify({ o: this.instanceId, room: conn.room, m: outboundMessage }),\n );\n }\n // 'snapshot' from a client → ignored\n }\n\n private onFanout(payload: string): void {\n // Off the serial queue on purpose: forward-only (no backend re-apply — the origin already applied to the\n // SHARED backend), and delivery is already ordered. Do not wrap this in roomQueues.\n let env: { o?: unknown; room?: unknown; m?: unknown };\n try {\n env = JSON.parse(payload);\n } catch {\n return;\n }\n if (typeof env.o !== 'string' || typeof env.room !== 'string' || typeof env.m !== 'string')\n return;\n if (env.o === this.instanceId) return; // our own publish — already forwarded locally\n const members = this.rooms.get(env.room);\n if (!members) return;\n const m = env.m;\n for (const id of members) {\n try {\n this.conns.get(id)?.send(m);\n } catch {\n /* a throwing socket must not break the fanout loop */\n }\n }\n }\n\n close(): void {\n this.fanoutUnsub();\n }\n}\n","import { applyOpToMap, type SyncOp } from '@fieldnotes/sync';\nimport type { CanvasElement } from '@fieldnotes/core';\nimport type { HubBackend } from './hub-backend';\n\nexport class MemoryHubBackend implements HubBackend {\n private rooms = new Map<string, Map<string, CanvasElement>>();\n\n private room(id: string): Map<string, CanvasElement> {\n let r = this.rooms.get(id);\n if (!r) {\n r = new Map();\n this.rooms.set(id, r);\n }\n return r;\n }\n\n async snapshot(room: string): Promise<CanvasElement[]> {\n return [...this.room(room).values()];\n }\n\n async get(room: string, id: string): Promise<CanvasElement | undefined> {\n return this.room(room).get(id);\n }\n\n async apply(room: string, op: SyncOp): Promise<void> {\n applyOpToMap(this.room(room), op);\n }\n}\n","export interface HubFanout {\r\n publish(payload: string): void;\r\n subscribe(handler: (payload: string) => void): () => void;\r\n close?(): void;\r\n}\r\n\r\nexport class InMemoryHubFanout implements HubFanout {\r\n private readonly handlers = new Set<(payload: string) => void>();\r\n\r\n publish(payload: string): void {\r\n for (const h of this.handlers) {\r\n try {\r\n h(payload);\r\n } catch {\r\n /* one throwing subscriber must not break the publish loop */\r\n }\r\n }\r\n }\r\n\r\n subscribe(handler: (payload: string) => void): () => void {\r\n this.handlers.add(handler);\r\n return () => this.handlers.delete(handler);\r\n }\r\n}\r\n","import { WebSocketServer } from 'ws';\nimport type { Server } from 'http';\nimport { SyncHub } from './sync-hub';\nimport type { HubBackend } from './hub-backend';\nimport type { HubFanout } from './hub-fanout';\nimport type { Authenticate } from './authenticate';\nimport type { Authorize } from './authorize';\n\nexport interface CreateSyncServerOptions {\n port?: number;\n server?: Server;\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n authenticate?: Authenticate;\n authorize?: Authorize;\n}\n\nexport function createSyncServer(options: CreateSyncServerOptions = {}): {\n hub: SyncHub;\n wss: WebSocketServer;\n close: () => Promise<void>;\n} {\n const hub = new SyncHub({\n backend: options.backend,\n fanout: options.fanout,\n instanceId: options.instanceId,\n authorize: options.authorize,\n });\n const wss = options.server\n ? new WebSocketServer({ server: options.server })\n : new WebSocketServer({ port: options.port ?? 0 });\n let counter = 0;\n wss.on('connection', (ws, req) => {\n const url = new URL(req.url ?? '', 'http://localhost');\n const room = url.searchParams.get('room');\n if (!room) {\n ws.close(1008, 'room required');\n return;\n }\n const connId = `c${++counter}-${Math.random().toString(36).slice(2, 8)}`;\n\n let state: 'pending' | 'ready' | 'rejected' = 'pending';\n let closed = false;\n const queue: string[] = [];\n const MAX_QUEUE = 100;\n\n const send = (m: string) => {\n try {\n ws.send(m);\n } catch {\n /* socket closed mid-send */\n }\n };\n\n ws.on('message', (data) => {\n const msg = String(data);\n if (state === 'rejected') return;\n if (state === 'pending') {\n if (queue.length < MAX_QUEUE) queue.push(msg);\n return;\n }\n void hub.handleMessage(connId, msg).catch((err) => console.error('[sync-server]', err));\n });\n ws.on('close', () => {\n closed = true;\n if (state === 'ready') hub.removeConnection(connId);\n });\n\n Promise.resolve(options.authenticate ? options.authenticate({ req, room }) : { userId: connId })\n .then((result) => {\n if (closed) return;\n if (!result) {\n state = 'rejected';\n ws.close(4401, 'unauthorized');\n return;\n }\n state = 'ready';\n hub.addConnection({ id: connId, room, userId: result.userId, role: result.role, send });\n for (const m of queue) {\n void hub.handleMessage(connId, m).catch((err) => console.error('[sync-server]', err));\n }\n queue.length = 0;\n })\n .catch(() => {\n if (!closed) {\n state = 'rejected';\n ws.close(4401, 'unauthorized');\n }\n });\n });\n return {\n hub,\n wss,\n close: () =>\n new Promise<void>((resol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MAAM,cAAc;AAC7B;AAAA,MACF;AACA,cAAQ;AACR,UAAI,cAAc,EAAE,IAAI,QAAQ,MAAM,QAAQ,OAAO,QAAQ,MAAM,OAAO,MAAM,KAAK,CAAC;AACtF,iBAAW,KAAK,OAAO;AACrB,aAAK,IAAI,cAAc,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,QAAQ,MAAM,iBAAiB,GAAG,CAAC;AAAA,MACtF;AACA,YAAM,SAAS;AAAA,IACjB,CAAC,EACA,MAAM,MAAM;AACX,UAAI,CAAC,QAAQ;AACX,gBAAQ;AACR,WAAG,MAAM,MAAM,cAAc;AAAA,MAC/B;AAAA,IACF,CAAC;AAAA,EACL,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MACL,IAAI,QAAc,CAAC,YAAY;AAC7B,UAAI,MAAM;AACV,UAAI,MAAM,MAAM,QAAQ,CAAC;AAAA,IAC3B,CAAC;AAAA,EACL;AACF;","names":["import_sync"]}
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CanvasElement } from '@fieldnotes/core';
2
2
  import { SyncOp } from '@fieldnotes/sync';
3
3
  import { WebSocketServer } from 'ws';
4
- import { Server } from 'http';
4
+ import { IncomingMessage, Server } from 'http';
5
5
 
6
6
  interface HubFanout {
7
7
  publish(payload: string): void;
@@ -16,18 +16,34 @@ declare class InMemoryHubFanout implements HubFanout {
16
16
 
17
17
  interface HubBackend {
18
18
  snapshot(room: string): Promise<CanvasElement[]>;
19
+ get(room: string, id: string): Promise<CanvasElement | undefined>;
19
20
  apply(room: string, op: SyncOp): Promise<void>;
20
21
  }
21
22
 
23
+ type OwnedElement = CanvasElement & {
24
+ ownerId?: string;
25
+ };
26
+ interface AuthorizeContext {
27
+ userId?: string;
28
+ role?: string;
29
+ room: string;
30
+ op: SyncOp;
31
+ currentElement?: OwnedElement;
32
+ }
33
+ type Authorize = (ctx: AuthorizeContext) => boolean | Promise<boolean>;
34
+
22
35
  interface Connection {
23
36
  id: string;
24
37
  room: string;
38
+ userId?: string;
39
+ role?: string;
25
40
  send(message: string): void;
26
41
  }
27
42
  interface SyncHubOptions {
28
43
  backend?: HubBackend;
29
44
  fanout?: HubFanout;
30
45
  instanceId?: string;
46
+ authorize?: Authorize;
31
47
  }
32
48
  declare class SyncHub {
33
49
  private readonly backend;
@@ -37,6 +53,7 @@ declare class SyncHub {
37
53
  private readonly instanceId;
38
54
  private readonly fanout;
39
55
  private readonly fanoutUnsub;
56
+ private readonly authorize?;
40
57
  constructor(options?: SyncHubOptions);
41
58
  addConnection(conn: Connection): void;
42
59
  removeConnection(connId: string): void;
@@ -51,15 +68,28 @@ declare class MemoryHubBackend implements HubBackend {
51
68
  private rooms;
52
69
  private room;
53
70
  snapshot(room: string): Promise<CanvasElement[]>;
71
+ get(room: string, id: string): Promise<CanvasElement | undefined>;
54
72
  apply(room: string, op: SyncOp): Promise<void>;
55
73
  }
56
74
 
75
+ interface AuthInfo {
76
+ req: IncomingMessage;
77
+ room: string;
78
+ }
79
+ interface AuthResult {
80
+ userId: string;
81
+ role?: string;
82
+ }
83
+ type Authenticate = (info: AuthInfo) => AuthResult | null | Promise<AuthResult | null>;
84
+
57
85
  interface CreateSyncServerOptions {
58
86
  port?: number;
59
87
  server?: Server;
60
88
  backend?: HubBackend;
61
89
  fanout?: HubFanout;
62
90
  instanceId?: string;
91
+ authenticate?: Authenticate;
92
+ authorize?: Authorize;
63
93
  }
64
94
  declare function createSyncServer(options?: CreateSyncServerOptions): {
65
95
  hub: SyncHub;
@@ -67,4 +97,4 @@ declare function createSyncServer(options?: CreateSyncServerOptions): {
67
97
  close: () => Promise<void>;
68
98
  };
69
99
 
70
- export { type Connection, type CreateSyncServerOptions, type HubBackend, type HubFanout, InMemoryHubFanout, MemoryHubBackend, SyncHub, type SyncHubOptions, createSyncServer };
100
+ export { type AuthInfo, type AuthResult, type Authenticate, type Authorize, type AuthorizeContext, type Connection, type CreateSyncServerOptions, type HubBackend, type HubFanout, InMemoryHubFanout, MemoryHubBackend, type OwnedElement, SyncHub, type SyncHubOptions, createSyncServer };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { CanvasElement } from '@fieldnotes/core';
2
2
  import { SyncOp } from '@fieldnotes/sync';
3
3
  import { WebSocketServer } from 'ws';
4
- import { Server } from 'http';
4
+ import { IncomingMessage, Server } from 'http';
5
5
 
6
6
  interface HubFanout {
7
7
  publish(payload: string): void;
@@ -16,18 +16,34 @@ declare class InMemoryHubFanout implements HubFanout {
16
16
 
17
17
  interface HubBackend {
18
18
  snapshot(room: string): Promise<CanvasElement[]>;
19
+ get(room: string, id: string): Promise<CanvasElement | undefined>;
19
20
  apply(room: string, op: SyncOp): Promise<void>;
20
21
  }
21
22
 
23
+ type OwnedElement = CanvasElement & {
24
+ ownerId?: string;
25
+ };
26
+ interface AuthorizeContext {
27
+ userId?: string;
28
+ role?: string;
29
+ room: string;
30
+ op: SyncOp;
31
+ currentElement?: OwnedElement;
32
+ }
33
+ type Authorize = (ctx: AuthorizeContext) => boolean | Promise<boolean>;
34
+
22
35
  interface Connection {
23
36
  id: string;
24
37
  room: string;
38
+ userId?: string;
39
+ role?: string;
25
40
  send(message: string): void;
26
41
  }
27
42
  interface SyncHubOptions {
28
43
  backend?: HubBackend;
29
44
  fanout?: HubFanout;
30
45
  instanceId?: string;
46
+ authorize?: Authorize;
31
47
  }
32
48
  declare class SyncHub {
33
49
  private readonly backend;
@@ -37,6 +53,7 @@ declare class SyncHub {
37
53
  private readonly instanceId;
38
54
  private readonly fanout;
39
55
  private readonly fanoutUnsub;
56
+ private readonly authorize?;
40
57
  constructor(options?: SyncHubOptions);
41
58
  addConnection(conn: Connection): void;
42
59
  removeConnection(connId: string): void;
@@ -51,15 +68,28 @@ declare class MemoryHubBackend implements HubBackend {
51
68
  private rooms;
52
69
  private room;
53
70
  snapshot(room: string): Promise<CanvasElement[]>;
71
+ get(room: string, id: string): Promise<CanvasElement | undefined>;
54
72
  apply(room: string, op: SyncOp): Promise<void>;
55
73
  }
56
74
 
75
+ interface AuthInfo {
76
+ req: IncomingMessage;
77
+ room: string;
78
+ }
79
+ interface AuthResult {
80
+ userId: string;
81
+ role?: string;
82
+ }
83
+ type Authenticate = (info: AuthInfo) => AuthResult | null | Promise<AuthResult | null>;
84
+
57
85
  interface CreateSyncServerOptions {
58
86
  port?: number;
59
87
  server?: Server;
60
88
  backend?: HubBackend;
61
89
  fanout?: HubFanout;
62
90
  instanceId?: string;
91
+ authenticate?: Authenticate;
92
+ authorize?: Authorize;
63
93
  }
64
94
  declare function createSyncServer(options?: CreateSyncServerOptions): {
65
95
  hub: SyncHub;
@@ -67,4 +97,4 @@ declare function createSyncServer(options?: CreateSyncServerOptions): {
67
97
  close: () => Promise<void>;
68
98
  };
69
99
 
70
- export { type Connection, type CreateSyncServerOptions, type HubBackend, type HubFanout, InMemoryHubFanout, MemoryHubBackend, SyncHub, type SyncHubOptions, createSyncServer };
100
+ export { type AuthInfo, type AuthResult, type Authenticate, type Authorize, type AuthorizeContext, type Connection, type CreateSyncServerOptions, type HubBackend, type HubFanout, InMemoryHubFanout, MemoryHubBackend, type OwnedElement, SyncHub, type SyncHubOptions, createSyncServer };
package/dist/index.js CHANGED
@@ -16,6 +16,9 @@ var MemoryHubBackend = class {
16
16
  async snapshot(room) {
17
17
  return [...this.room(room).values()];
18
18
  }
19
+ async get(room, id) {
20
+ return this.room(room).get(id);
21
+ }
19
22
  async apply(room, op) {
20
23
  applyOpToMap(this.room(room), op);
21
24
  }
@@ -55,10 +58,12 @@ var SyncHub = class {
55
58
  instanceId;
56
59
  fanout;
57
60
  fanoutUnsub;
61
+ authorize;
58
62
  constructor(options = {}) {
59
63
  this.backend = options.backend ?? new MemoryHubBackend();
60
64
  this.instanceId = options.instanceId ?? generateInstanceId();
61
65
  this.fanout = options.fanout ?? new InMemoryHubFanout();
66
+ this.authorize = options.authorize;
62
67
  this.fanoutUnsub = this.fanout.subscribe((payload) => this.onFanout(payload));
63
68
  }
64
69
  addConnection(conn) {
@@ -106,15 +111,37 @@ var SyncHub = class {
106
111
  JSON.stringify({ from: HUB_FROM, op: { kind: "snapshot", to: env.from, elements } })
107
112
  );
108
113
  } else if (op.kind === "upsert" || op.kind === "remove" || op.kind === "clear") {
109
- await this.backend.apply(conn.room, op);
114
+ let outboundOp = op;
115
+ let outboundMessage = message;
116
+ if (this.authorize) {
117
+ const id = op.kind === "upsert" ? op.element.id : op.kind === "remove" ? op.id : void 0;
118
+ const current = id !== void 0 ? await this.backend.get(conn.room, id) : void 0;
119
+ const allowed = await this.authorize({
120
+ userId: conn.userId,
121
+ role: conn.role,
122
+ room: conn.room,
123
+ op,
124
+ currentElement: current
125
+ });
126
+ if (!allowed) return;
127
+ if (op.kind === "upsert") {
128
+ const ownerId = current?.ownerId ?? conn.userId;
129
+ const stampedElement = { ...op.element, ownerId };
130
+ outboundOp = { kind: "upsert", element: stampedElement };
131
+ outboundMessage = JSON.stringify({ from: env.from, op: outboundOp });
132
+ }
133
+ }
134
+ await this.backend.apply(conn.room, outboundOp);
110
135
  const members = this.rooms.get(conn.room);
111
136
  if (members) {
112
137
  for (const id of members) {
113
138
  if (id === conn.id) continue;
114
- this.conns.get(id)?.send(message);
139
+ this.conns.get(id)?.send(outboundMessage);
115
140
  }
116
141
  }
117
- this.fanout.publish(JSON.stringify({ o: this.instanceId, room: conn.room, m: message }));
142
+ this.fanout.publish(
143
+ JSON.stringify({ o: this.instanceId, room: conn.room, m: outboundMessage })
144
+ );
118
145
  }
119
146
  }
120
147
  onFanout(payload) {
@@ -148,7 +175,8 @@ function createSyncServer(options = {}) {
148
175
  const hub = new SyncHub({
149
176
  backend: options.backend,
150
177
  fanout: options.fanout,
151
- instanceId: options.instanceId
178
+ instanceId: options.instanceId,
179
+ authorize: options.authorize
152
180
  });
153
181
  const wss = options.server ? new WebSocketServer({ server: options.server }) : new WebSocketServer({ port: options.port ?? 0 });
154
182
  let counter = 0;
@@ -160,20 +188,48 @@ function createSyncServer(options = {}) {
160
188
  return;
161
189
  }
162
190
  const connId = `c${++counter}-${Math.random().toString(36).slice(2, 8)}`;
163
- hub.addConnection({
164
- id: connId,
165
- room,
166
- send: (m) => {
167
- try {
168
- ws.send(m);
169
- } catch {
170
- }
191
+ let state = "pending";
192
+ let closed = false;
193
+ const queue = [];
194
+ const MAX_QUEUE = 100;
195
+ const send = (m) => {
196
+ try {
197
+ ws.send(m);
198
+ } catch {
171
199
  }
172
- });
200
+ };
173
201
  ws.on("message", (data) => {
174
- void hub.handleMessage(connId, String(data)).catch((err) => console.error("[sync-server]", err));
202
+ const msg = String(data);
203
+ if (state === "rejected") return;
204
+ if (state === "pending") {
205
+ if (queue.length < MAX_QUEUE) queue.push(msg);
206
+ return;
207
+ }
208
+ void hub.handleMessage(connId, msg).catch((err) => console.error("[sync-server]", err));
209
+ });
210
+ ws.on("close", () => {
211
+ closed = true;
212
+ if (state === "ready") hub.removeConnection(connId);
213
+ });
214
+ Promise.resolve(options.authenticate ? options.authenticate({ req, room }) : { userId: connId }).then((result) => {
215
+ if (closed) return;
216
+ if (!result) {
217
+ state = "rejected";
218
+ ws.close(4401, "unauthorized");
219
+ return;
220
+ }
221
+ state = "ready";
222
+ hub.addConnection({ id: connId, room, userId: result.userId, role: result.role, send });
223
+ for (const m of queue) {
224
+ void hub.handleMessage(connId, m).catch((err) => console.error("[sync-server]", err));
225
+ }
226
+ queue.length = 0;
227
+ }).catch(() => {
228
+ if (!closed) {
229
+ state = "rejected";
230
+ ws.close(4401, "unauthorized");
231
+ }
175
232
  });
176
- ws.on("close", () => hub.removeConnection(connId));
177
233
  });
178
234
  return {
179
235
  hub,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sync-hub.ts","../src/memory-hub-backend.ts","../src/hub-fanout.ts","../src/create-sync-server.ts"],"sourcesContent":["import { parseEnvelope } from '@fieldnotes/sync';\nimport { MemoryHubBackend } from './memory-hub-backend';\nimport { InMemoryHubFanout, type HubFanout } from './hub-fanout';\nimport type { HubBackend } from './hub-backend';\n\nexport interface Connection {\n id: string;\n room: string;\n send(message: string): void;\n}\n\nexport interface SyncHubOptions {\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n}\n\nconst HUB_FROM = 'hub';\n\nfunction generateInstanceId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')\n return crypto.randomUUID();\n return `i-${Math.random().toString(36).slice(2)}`;\n}\n\nexport class SyncHub {\n private readonly backend: HubBackend;\n private readonly conns = new Map<string, Connection>();\n private readonly rooms = new Map<string, Set<string>>(); // room → connIds\n private readonly roomQueues = new Map<string, Promise<void>>(); // room → serial tail\n private readonly instanceId: string;\n private readonly fanout: HubFanout;\n private readonly fanoutUnsub: () => void;\n\n constructor(options: SyncHubOptions = {}) {\n this.backend = options.backend ?? new MemoryHubBackend();\n this.instanceId = options.instanceId ?? generateInstanceId();\n this.fanout = options.fanout ?? new InMemoryHubFanout();\n this.fanoutUnsub = this.fanout.subscribe((payload) => this.onFanout(payload));\n }\n\n addConnection(conn: Connection): void {\n this.conns.set(conn.id, conn);\n let set = this.rooms.get(conn.room);\n if (!set) {\n set = new Set();\n this.rooms.set(conn.room, set);\n }\n set.add(conn.id);\n }\n\n removeConnection(connId: string): void {\n const conn = this.conns.get(connId);\n if (!conn) return;\n this.conns.delete(connId);\n const members = this.rooms.get(conn.room);\n if (members) {\n members.delete(connId);\n if (members.size === 0) {\n this.rooms.delete(conn.room);\n this.roomQueues.delete(conn.room);\n }\n }\n }\n\n roomCount(): number {\n return this.rooms.size;\n }\n\n handleMessage(connId: string, message: string): Promise<void> {\n const conn = this.conns.get(connId);\n if (!conn) return Promise.resolve();\n const room = conn.room;\n const prev = this.roomQueues.get(room) ?? Promise.resolve();\n const next = prev\n .then(() => this.process(conn, message))\n .catch(() => {\n // swallow so one failed message never wedges the room's serial queue\n });\n this.roomQueues.set(room, next);\n return next;\n }\n\n private async process(conn: Connection, message: string): Promise<void> {\n const env = parseEnvelope(message);\n if (!env) return;\n const op = env.op;\n if (op.kind === 'request-snapshot') {\n const elements = await this.backend.snapshot(conn.room);\n conn.send(\n JSON.stringify({ from: HUB_FROM, op: { kind: 'snapshot', to: env.from, elements } }),\n );\n } else if (op.kind === 'upsert' || op.kind === 'remove' || op.kind === 'clear') {\n await this.backend.apply(conn.room, op);\n const members = this.rooms.get(conn.room);\n if (members) {\n for (const id of members) {\n if (id === conn.id) continue;\n this.conns.get(id)?.send(message);\n }\n }\n this.fanout.publish(JSON.stringify({ o: this.instanceId, room: conn.room, m: message }));\n }\n // 'snapshot' from a client → ignored\n }\n\n private onFanout(payload: string): void {\n // Off the serial queue on purpose: forward-only (no backend re-apply — the origin already applied to the\n // SHARED backend), and delivery is already ordered. Do not wrap this in roomQueues.\n let env: { o?: unknown; room?: unknown; m?: unknown };\n try {\n env = JSON.parse(payload);\n } catch {\n return;\n }\n if (typeof env.o !== 'string' || typeof env.room !== 'string' || typeof env.m !== 'string')\n return;\n if (env.o === this.instanceId) return; // our own publish — already forwarded locally\n const members = this.rooms.get(env.room);\n if (!members) return;\n const m = env.m;\n for (const id of members) {\n try {\n this.conns.get(id)?.send(m);\n } catch {\n /* a throwing socket must not break the fanout loop */\n }\n }\n }\n\n close(): void {\n this.fanoutUnsub();\n }\n}\n","import { applyOpToMap, type SyncOp } from '@fieldnotes/sync';\r\nimport type { CanvasElement } from '@fieldnotes/core';\r\nimport type { HubBackend } from './hub-backend';\r\n\r\nexport class MemoryHubBackend implements HubBackend {\r\n private rooms = new Map<string, Map<string, CanvasElement>>();\r\n\r\n private room(id: string): Map<string, CanvasElement> {\r\n let r = this.rooms.get(id);\r\n if (!r) {\r\n r = new Map();\r\n this.rooms.set(id, r);\r\n }\r\n return r;\r\n }\r\n\r\n async snapshot(room: string): Promise<CanvasElement[]> {\r\n return [...this.room(room).values()];\r\n }\r\n\r\n async apply(room: string, op: SyncOp): Promise<void> {\r\n applyOpToMap(this.room(room), op);\r\n }\r\n}\r\n","export interface HubFanout {\n publish(payload: string): void;\n subscribe(handler: (payload: string) => void): () => void;\n close?(): void;\n}\n\nexport class InMemoryHubFanout implements HubFanout {\n private readonly handlers = new Set<(payload: string) => void>();\n\n publish(payload: string): void {\n for (const h of this.handlers) {\n try {\n h(payload);\n } catch {\n /* one throwing subscriber must not break the publish loop */\n }\n }\n }\n\n subscribe(handler: (payload: string) => void): () => void {\n this.handlers.add(handler);\n return () => this.handlers.delete(handler);\n }\n}\n","import { WebSocketServer } from 'ws';\nimport type { Server } from 'http';\nimport { SyncHub } from './sync-hub';\nimport type { HubBackend } from './hub-backend';\nimport type { HubFanout } from './hub-fanout';\n\nexport interface CreateSyncServerOptions {\n port?: number;\n server?: Server;\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n}\n\nexport function createSyncServer(options: CreateSyncServerOptions = {}): {\n hub: SyncHub;\n wss: WebSocketServer;\n close: () => Promise<void>;\n} {\n const hub = new SyncHub({\n backend: options.backend,\n fanout: options.fanout,\n instanceId: options.instanceId,\n });\n const wss = options.server\n ? new WebSocketServer({ server: options.server })\n : new WebSocketServer({ port: options.port ?? 0 });\n let counter = 0;\n wss.on('connection', (ws, req) => {\n const url = new URL(req.url ?? '', 'http://localhost');\n const room = url.searchParams.get('room');\n if (!room) {\n ws.close(1008, 'room required');\n return;\n }\n const connId = `c${++counter}-${Math.random().toString(36).slice(2, 8)}`;\n hub.addConnection({\n id: connId,\n room,\n send: (m) => {\n try {\n ws.send(m);\n } catch {\n /* socket closed mid-send */\n }\n },\n });\n ws.on('message', (data) => {\n void hub\n .handleMessage(connId, String(data))\n .catch((err) => console.error('[sync-server]', err));\n });\n ws.on('close', () => hub.removeConnection(connId));\n });\n return {\n hub,\n wss,\n close: () =>\n new Promise<void>((resolve) => {\n hub.close();\n wss.close(() => resolve());\n }),\n };\n}\n"],"mappings":";AAAA,SAAS,qBAAqB;;;ACA9B,SAAS,oBAAiC;AAInC,IAAM,mBAAN,MAA6C;AAAA,EAC1C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"sources":["../src/sync-hub.ts","../src/memory-hub-backend.ts","../src/hub-fanout.ts","../src/create-sync-server.ts"],"sourcesContent":["import { parseEnvelope, type SyncOp } from '@fieldnotes/sync';\nimport { MemoryHubBackend } from './memory-hub-backend';\nimport { InMemoryHubFanout, type HubFanout } from './hub-fanout';\nimport type { HubBackend } from './hub-backend';\nimport type { Authorize, OwnedElement } from './authorize';\n\nexport interface Connection {\n id: string;\n room: string;\n userId?: string;\n role?: string;\n send(message: string): void;\n}\n\nexport interface SyncHubOptions {\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n authorize?: Authorize;\n}\n\nconst HUB_FROM = 'hub';\n\nfunction generateInstanceId(): string {\n if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function')\n return crypto.randomUUID();\n return `i-${Math.random().toString(36).slice(2)}`;\n}\n\nexport class SyncHub {\n private readonly backend: HubBackend;\n private readonly conns = new Map<string, Connection>();\n private readonly rooms = new Map<string, Set<string>>(); // room → connIds\n private readonly roomQueues = new Map<string, Promise<void>>(); // room → serial tail\n private readonly instanceId: string;\n private readonly fanout: HubFanout;\n private readonly fanoutUnsub: () => void;\n private readonly authorize?: Authorize;\n\n constructor(options: SyncHubOptions = {}) {\n this.backend = options.backend ?? new MemoryHubBackend();\n this.instanceId = options.instanceId ?? generateInstanceId();\n this.fanout = options.fanout ?? new InMemoryHubFanout();\n this.authorize = options.authorize;\n this.fanoutUnsub = this.fanout.subscribe((payload) => this.onFanout(payload));\n }\n\n addConnection(conn: Connection): void {\n this.conns.set(conn.id, conn);\n let set = this.rooms.get(conn.room);\n if (!set) {\n set = new Set();\n this.rooms.set(conn.room, set);\n }\n set.add(conn.id);\n }\n\n removeConnection(connId: string): void {\n const conn = this.conns.get(connId);\n if (!conn) return;\n this.conns.delete(connId);\n const members = this.rooms.get(conn.room);\n if (members) {\n members.delete(connId);\n if (members.size === 0) {\n this.rooms.delete(conn.room);\n this.roomQueues.delete(conn.room);\n }\n }\n }\n\n roomCount(): number {\n return this.rooms.size;\n }\n\n handleMessage(connId: string, message: string): Promise<void> {\n const conn = this.conns.get(connId);\n if (!conn) return Promise.resolve();\n const room = conn.room;\n const prev = this.roomQueues.get(room) ?? Promise.resolve();\n const next = prev\n .then(() => this.process(conn, message))\n .catch(() => {\n // swallow so one failed message never wedges the room's serial queue\n });\n this.roomQueues.set(room, next);\n return next;\n }\n\n private async process(conn: Connection, message: string): Promise<void> {\n const env = parseEnvelope(message);\n if (!env) return;\n const op = env.op;\n if (op.kind === 'request-snapshot') {\n const elements = await this.backend.snapshot(conn.room);\n conn.send(\n JSON.stringify({ from: HUB_FROM, op: { kind: 'snapshot', to: env.from, elements } }),\n );\n } else if (op.kind === 'upsert' || op.kind === 'remove' || op.kind === 'clear') {\n let outboundOp: SyncOp = op;\n let outboundMessage = message;\n if (this.authorize) {\n const id = op.kind === 'upsert' ? op.element.id : op.kind === 'remove' ? op.id : undefined;\n const current: OwnedElement | undefined =\n id !== undefined ? await this.backend.get(conn.room, id) : undefined;\n const allowed = await this.authorize({\n userId: conn.userId,\n role: conn.role,\n room: conn.room,\n op,\n currentElement: current,\n });\n if (!allowed) return;\n if (op.kind === 'upsert') {\n const ownerId = current?.ownerId ?? conn.userId;\n const stampedElement: OwnedElement = { ...op.element, ownerId };\n outboundOp = { kind: 'upsert', element: stampedElement };\n outboundMessage = JSON.stringify({ from: env.from, op: outboundOp });\n }\n }\n await this.backend.apply(conn.room, outboundOp);\n const members = this.rooms.get(conn.room);\n if (members) {\n for (const id of members) {\n if (id === conn.id) continue;\n this.conns.get(id)?.send(outboundMessage);\n }\n }\n this.fanout.publish(\n JSON.stringify({ o: this.instanceId, room: conn.room, m: outboundMessage }),\n );\n }\n // 'snapshot' from a client → ignored\n }\n\n private onFanout(payload: string): void {\n // Off the serial queue on purpose: forward-only (no backend re-apply — the origin already applied to the\n // SHARED backend), and delivery is already ordered. Do not wrap this in roomQueues.\n let env: { o?: unknown; room?: unknown; m?: unknown };\n try {\n env = JSON.parse(payload);\n } catch {\n return;\n }\n if (typeof env.o !== 'string' || typeof env.room !== 'string' || typeof env.m !== 'string')\n return;\n if (env.o === this.instanceId) return; // our own publish — already forwarded locally\n const members = this.rooms.get(env.room);\n if (!members) return;\n const m = env.m;\n for (const id of members) {\n try {\n this.conns.get(id)?.send(m);\n } catch {\n /* a throwing socket must not break the fanout loop */\n }\n }\n }\n\n close(): void {\n this.fanoutUnsub();\n }\n}\n","import { applyOpToMap, type SyncOp } from '@fieldnotes/sync';\nimport type { CanvasElement } from '@fieldnotes/core';\nimport type { HubBackend } from './hub-backend';\n\nexport class MemoryHubBackend implements HubBackend {\n private rooms = new Map<string, Map<string, CanvasElement>>();\n\n private room(id: string): Map<string, CanvasElement> {\n let r = this.rooms.get(id);\n if (!r) {\n r = new Map();\n this.rooms.set(id, r);\n }\n return r;\n }\n\n async snapshot(room: string): Promise<CanvasElement[]> {\n return [...this.room(room).values()];\n }\n\n async get(room: string, id: string): Promise<CanvasElement | undefined> {\n return this.room(room).get(id);\n }\n\n async apply(room: string, op: SyncOp): Promise<void> {\n applyOpToMap(this.room(room), op);\n }\n}\n","export interface HubFanout {\r\n publish(payload: string): void;\r\n subscribe(handler: (payload: string) => void): () => void;\r\n close?(): void;\r\n}\r\n\r\nexport class InMemoryHubFanout implements HubFanout {\r\n private readonly handlers = new Set<(payload: string) => void>();\r\n\r\n publish(payload: string): void {\r\n for (const h of this.handlers) {\r\n try {\r\n h(payload);\r\n } catch {\r\n /* one throwing subscriber must not break the publish loop */\r\n }\r\n }\r\n }\r\n\r\n subscribe(handler: (payload: string) => void): () => void {\r\n this.handlers.add(handler);\r\n return () => this.handlers.delete(handler);\r\n }\r\n}\r\n","import { WebSocketServer } from 'ws';\nimport type { Server } from 'http';\nimport { SyncHub } from './sync-hub';\nimport type { HubBackend } from './hub-backend';\nimport type { HubFanout } from './hub-fanout';\nimport type { Authenticate } from './authenticate';\nimport type { Authorize } from './authorize';\n\nexport interface CreateSyncServerOptions {\n port?: number;\n server?: Server;\n backend?: HubBackend;\n fanout?: HubFanout;\n instanceId?: string;\n authenticate?: Authenticate;\n authorize?: Authorize;\n}\n\nexport function createSyncServer(options: CreateSyncServerOptions = {}): {\n hub: SyncHub;\n wss: WebSocketServer;\n close: () => Promise<void>;\n} {\n const hub = new SyncHub({\n backend: options.backend,\n fanout: options.fanout,\n instanceId: options.instanceId,\n authorize: options.authorize,\n });\n const wss = options.server\n ? new WebSocketServer({ server: options.server })\n : new WebSocketServer({ port: options.port ?? 0 });\n let counter = 0;\n wss.on('connection', (ws, req) => {\n const url = new URL(req.url ?? '', 'http://localhost');\n const room = url.searchParams.get('room');\n if (!room) {\n ws.close(1008, 'room required');\n return;\n }\n const connId = `c${++counter}-${Math.random().toString(36).slice(2, 8)}`;\n\n let state: 'pending' | 'ready' | 'rejected' = 'pending';\n let closed = false;\n const queue: string[] = [];\n const MAX_QUEUE = 100;\n\n const send = (m: string) => {\n try {\n ws.send(m);\n } catch {\n /* socket closed mid-send */\n }\n };\n\n ws.on('message', (data) => {\n const msg = String(data);\n if (state === 'rejected') return;\n if (state === 'pending') {\n if (queue.length < MAX_QUEUE) queue.push(msg);\n return;\n }\n void hub.handleMessage(connId, msg).catch((err) => console.error('[sync-server]', err));\n });\n ws.on('close', () => {\n closed = true;\n if (state === 'ready') hub.removeConnection(connId);\n });\n\n Promise.resolve(options.authenticate ? options.authenticate({ req, room }) : { userId: connId })\n .then((result) => {\n if (closed) return;\n if (!result) {\n state = 'rejected';\n ws.close(4401, 'unauthorized');\n return;\n }\n state = 'ready';\n hub.addConnection({ id: connId, room, userId: result.userId, role: result.role, send });\n for (const m of queue) {\n void hub.handleMessage(connId, m).catch((err) => console.error('[sync-server]', err));\n }\n queue.length = 0;\n })\n .catch(() => {\n if (!closed) {\n state = 'rejected';\n ws.close(4401, 'unauthorized');\n }\n });\n });\n return {\n hub,\n wss,\n close: () =>\n new Promise<void>((resolve) => {\n hub.close();\n wss.close(() => resolve());\n }),\n };\n}\n"],"mappings":";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,MAAM,KAAK,CAAC;AACtF,iBAAW,KAAK,OAAO;AACrB,aAAK,IAAI,cAAc,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,QAAQ,MAAM,iBAAiB,GAAG,CAAC;AAAA,MACtF;AACA,YAAM,SAAS;AAAA,IACjB,CAAC,EACA,MAAM,MAAM;AACX,UAAI,CAAC,QAAQ;AACX,gBAAQ;AACR,WAAG,MAAM,MAAM,cAAc;AAAA,MAC/B;AAAA,IACF,CAAC;AAAA,EACL,CAAC;AACD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OAAO,MACL,IAAI,QAAc,CAAC,YAAY;AAC7B,UAAI,MAAM;AACV,UAAI,MAAM,MAAM,QAAQ,CAAC;AAAA,IAC3B,CAAC;AAAA,EACL;AACF;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fieldnotes/sync-server",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Authoritative WebSocket relay server for Field Notes real-time sync",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -38,7 +38,7 @@
38
38
  ],
39
39
  "dependencies": {
40
40
  "ws": "^8.18.0",
41
- "@fieldnotes/sync": "0.4.0"
41
+ "@fieldnotes/sync": "0.5.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@types/ws": "^8.5.12",