@cardonjs/realtime-do 0.0.0-stage → 0.3.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
@@ -1,3 +1,805 @@
1
- # Temporary Holding Version
1
+ # @cardonjs/realtime-do
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Real-time for Cardón apps on Cloudflare Durable Objects. A room holds hibernating WebSockets;
4
+ the API publishes small events to it after saving data; a reconnecting browser client receives
5
+ them and reloads what changed.
6
+
7
+ The WebSocket only signals "something changed". Events flow server → client and carry a hint
8
+ (ids), never the record itself. The database stays the source of truth: a client that
9
+ reconnects, or that missed events, reloads its state through the API.
10
+
11
+ - `defineRoom(options)` returns the Durable Object class to export from the Worker entry. It is
12
+ a plain class (no `cloudflare:workers` import, no RPC); the Worker talks to it through the
13
+ binding with internal `fetch` requests.
14
+ - `connectToRoom(namespace, room, request, options)` opens a socket from a route, after the
15
+ route authenticated the caller and authorized the room. Channels are chosen by the server.
16
+ - `issueRoomTicket(namespace, room, options)` and `connectToRoomWithTicket(namespace, room,
17
+ request, options)`: the same for a client without a same-site cookie (an access token
18
+ holder), through a one-time ticket (see [Clients without a cookie](#clients-without-a-cookie-tickets)).
19
+ - `realtime(namespace)` returns a `RealtimePublisher` (`publish`, `count`, `disconnect`,
20
+ `presence`) for the adapters factory.
21
+ - `@cardonjs/realtime-do/client`: `createRealtimeClient`, zero dependencies, for browsers.
22
+ - `@cardonjs/realtime-do/testing`: `memoryRealtime()`, an in-memory fake publisher.
23
+
24
+ Peer dependencies: `@cardonjs/core`. Types for `DurableObjectNamespace` and `DurableObjectState`
25
+ come from `@cloudflare/workers-types` (as in `@cardonjs/config/tsconfig.workers.json`). The client
26
+ needs only the DOM types.
27
+
28
+ For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
29
+
30
+ ## Wrangler configuration
31
+
32
+ Bind the room class and create it with a migration (`new_sqlite_classes`: the room stores
33
+ only short-lived revocation markers and pending tickets, and new classes should use the SQLite
34
+ backend, the only one on the free plan). Tickets (below) need it: they use its synchronous
35
+ storage, and on a room class created with `new_classes` `issueRoomTicket` and
36
+ `connectToRoomWithTicket` throw an `Error` saying so. Everything else works on either backend.
37
+
38
+ ```toml
39
+ [[durable_objects.bindings]]
40
+ name = "BOARD_ROOMS"
41
+ class_name = "BoardRoom"
42
+
43
+ [[migrations]]
44
+ tag = "v1"
45
+ new_sqlite_classes = ["BoardRoom"]
46
+ ```
47
+
48
+ The connect route is rate limited per user with a
49
+ [rate limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
50
+ (`period` is 10 or 60 seconds, and `workersRateLimiter` gets the same value):
51
+
52
+ ```toml
53
+ [[ratelimits]]
54
+ name = "CONNECT_LIMITER"
55
+ # Scoped to the Cloudflare account, not the Worker: unique per app, environment and limit.
56
+ namespace_id = "1301"
57
+ simple = { limit = 20, period = 60 }
58
+ ```
59
+
60
+ ## Worker
61
+
62
+ The example is a board app: members of a board see cards appear live. The room name is built
63
+ by the server from the board id (`board:<id>`), one Durable Object per board.
64
+
65
+ ```ts
66
+ import { getIdentity, requireAuth } from "@cardonjs/auth";
67
+ import {
68
+ type CardonEnv,
69
+ createApp,
70
+ created,
71
+ defineModule,
72
+ errorEnvelopeSchema,
73
+ ForbiddenError,
74
+ idSchema,
75
+ newId,
76
+ rateLimit,
77
+ rateLimitKeys,
78
+ successEnvelope,
79
+ workersRateLimiter,
80
+ } from "@cardonjs/core";
81
+ import { connectToRoom, defineRoom, realtime } from "@cardonjs/realtime-do";
82
+ import { createRoute, z } from "@hono/zod-openapi";
83
+
84
+ type Bindings = {
85
+ BOARD_ROOMS: DurableObjectNamespace;
86
+ CONNECT_LIMITER: RateLimit;
87
+ APP_ORIGIN: string;
88
+ DB: D1Database;
89
+ };
90
+ const adapters = (env: Bindings) => ({
91
+ auth: sessionCookieAuth(env), // your Authenticator: a same-site session cookie
92
+ boards: boardsRepository(env.DB), // your data access
93
+ live: realtime(env.BOARD_ROOMS),
94
+ connects: workersRateLimiter(env.CONNECT_LIMITER, { periodSeconds: 60 }),
95
+ });
96
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
97
+
98
+ const boardParams = z.object({ boardId: idSchema });
99
+ const card = z.object({ id: z.string(), title: z.string() });
100
+ const errors = {
101
+ 403: {
102
+ description: "Not a member of the board",
103
+ content: { "application/json": { schema: errorEnvelopeSchema } },
104
+ },
105
+ };
106
+
107
+ const liveRoute = createRoute({
108
+ method: "get",
109
+ path: "/{boardId}/live",
110
+ tags: ["Boards"],
111
+ summary: "Open the board's live updates (WebSocket upgrade)",
112
+ // Per user, after the guard: saves the room wake-up and the membership query of each upgrade
113
+ // (the guard already ran; the app's global per-IP `rateLimit` is what bounds authentication).
114
+ middleware: rateLimit<AppEnv>({
115
+ name: "board-live",
116
+ limiter: (c) => c.var.adapters.connects,
117
+ key: rateLimitKeys.identity,
118
+ }),
119
+ request: { params: boardParams },
120
+ responses: {
121
+ 101: { description: "Switching to the WebSocket protocol" },
122
+ 400: {
123
+ description: "Not a WebSocket upgrade",
124
+ content: { "application/json": { schema: errorEnvelopeSchema } },
125
+ },
126
+ 429: {
127
+ description: "Too many connects, or too many connections",
128
+ content: { "application/json": { schema: errorEnvelopeSchema } },
129
+ },
130
+ ...errors,
131
+ },
132
+ });
133
+
134
+ const addCardRoute = createRoute({
135
+ method: "post",
136
+ path: "/{boardId}/cards",
137
+ tags: ["Boards"],
138
+ summary: "Add a card",
139
+ request: {
140
+ params: boardParams,
141
+ body: {
142
+ required: true,
143
+ content: { "application/json": { schema: z.object({ title: z.string().min(1).max(200) }) } },
144
+ },
145
+ },
146
+ responses: {
147
+ 201: {
148
+ description: "The new card",
149
+ content: { "application/json": { schema: successEnvelope(card) } },
150
+ },
151
+ ...errors,
152
+ },
153
+ });
154
+
155
+ const boardsModule = defineModule<AppEnv>({
156
+ name: "boards",
157
+ prefix: "/v1/boards",
158
+ routes: (app) => {
159
+ app.openapi(liveRoute, async (c) => {
160
+ const { boardId } = c.req.valid("param");
161
+ const identity = getIdentity(c); // requireAuth already ran: no session, no socket
162
+ // The app's own authorization of this room.
163
+ if (!(await c.var.adapters.boards.isMember(boardId, identity.id))) {
164
+ throw new ForbiddenError();
165
+ }
166
+ return connectToRoom(c.env.BOARD_ROOMS, `board:${boardId}`, c.req.raw, {
167
+ identity, // only id and kind reach the room
168
+ channels: ["cards"], // chosen by the server, never by the client
169
+ allowedOrigins: [c.env.APP_ORIGIN], // e.g. "https://app.example.com"
170
+ });
171
+ });
172
+
173
+ app.openapi(addCardRoute, async (c) => {
174
+ const { boardId } = c.req.valid("param");
175
+ const identity = getIdentity(c);
176
+ if (!(await c.var.adapters.boards.isMember(boardId, identity.id))) {
177
+ throw new ForbiddenError();
178
+ }
179
+ const saved = { id: newId(), title: c.req.valid("json").title };
180
+ await c.var.adapters.boards.addCard(boardId, saved);
181
+ // A signal after the data is saved: a failed publish must not fail the request.
182
+ c.executionCtx.waitUntil(
183
+ c.var.adapters.live
184
+ .publish(`board:${boardId}`, {
185
+ channel: "cards",
186
+ type: "card.created",
187
+ data: { id: saved.id },
188
+ })
189
+ .catch(() => c.var.logger.warn("realtime publish failed", { boardId })),
190
+ );
191
+ return created(c, saved);
192
+ });
193
+ },
194
+ });
195
+
196
+ const app = createApp(adapters, {
197
+ guard: requireAuth<AppEnv>({ authenticator: (c) => c.var.adapters.auth }),
198
+ }).register(boardsModule);
199
+
200
+ // The Durable Object class, exported under the `class_name` of the Wrangler config.
201
+ export const BoardRoom = defineRoom<Bindings>();
202
+
203
+ export default app;
204
+ ```
205
+
206
+ `connectToRoom` throws the core errors, so the app's error handler answers with the usual
207
+ envelope:
208
+
209
+ | Case | Error |
210
+ | --- | --- |
211
+ | Not a `GET` with `Upgrade: websocket` | `ValidationError` (400) |
212
+ | `Origin` missing or not exactly in `allowedOrigins` | `ForbiddenError` (403) |
213
+ | Room full, the identity has too many connections, or it was disconnected less than 60 s ago | `RateLimitedError` (429) |
214
+
215
+ The route's `rateLimit` (from `@cardonjs/core`) runs before the handler, after the guard: more
216
+ than 20 connects a minute from one user also answer `429` (with `Retry-After`), before the
217
+ membership check or the room are reached. It runs after the guard, so it does not bound the
218
+ cost of authentication; the app's `rateLimit` option (per IP, before the guard) does. The
219
+ binding counts per Cloudflare location and is approximate, which is enough to stop a reconnect
220
+ loop or a script; the room's own limits above stay exact.
221
+
222
+ The `Origin` check matters: browsers send the session cookie on a cross-site WebSocket
223
+ upgrade, so without it any site could open a socket as the user (cross-site WebSocket
224
+ hijacking). `allowedOrigins` is required and holds exact origins (`https://host[:port]`); an
225
+ empty list or `"*"` throws when the route runs. `http:` origins are accepted only for local
226
+ development (`localhost`, `*.localhost`, `127.0.0.1`, `[::1]`); any other `http:` origin
227
+ throws.
228
+
229
+ **Authorize in the route.** The membership check above is what keeps a user out of a room.
230
+ `onConnect` (see [Room options](#room-options)) runs after the socket is accepted and is not a
231
+ gate: if it throws, the error is logged and the connection stays.
232
+
233
+ The room trusts what the Worker sends: it is reachable only through the binding, and the connect
234
+ request is rebuilt by `connectToRoom` (no client header reaches it). **Never forward a client
235
+ request to the room stub** (`stub.fetch(c.req.raw)`, or any route that proxies to it): the room
236
+ would trust whatever that request says, identity included. Only `connectToRoom` and
237
+ `realtime()` may call it.
238
+
239
+ Authentication happens in the route, once per connection; `maxConnectionAgeSeconds` makes
240
+ clients come back through the route to authenticate again. After removing a user from the
241
+ board, `disconnect` closes their sockets on that room and shuts the door for a moment:
242
+
243
+ ```ts
244
+ await c.var.adapters.live.disconnect(`board:${boardId}`, { id: removedUserId, kind: "user" });
245
+ ```
246
+
247
+ It closes the identity's open sockets with 4001 and, for the next 60 seconds, the room refuses
248
+ that identity's connects (429). That covers a connect that passed the membership check just
249
+ before the removal and reaches the room just after it. If the user is added back within those
250
+ 60 seconds, their client reconnects once the window has passed (it retries with backoff).
251
+
252
+ ## Room options
253
+
254
+ ```ts
255
+ export const BoardRoom = defineRoom<Bindings>({
256
+ maxConnections: 1000, // per room
257
+ maxConnectionsPerIdentity: 5,
258
+ maxEventBytes: 16_384, // serialized frame, UTF-8 bytes
259
+ maxConnectionAgeSeconds: 3600,
260
+ // Optional hooks, also `onConnect`. They get
261
+ // `{ room, identity, channels, connectedAt, connections, identityConnections, env }`;
262
+ // `connections` is the open count after the change: 0 means the room is now empty.
263
+ onDisconnect: async ({ room, connections, env }) => {
264
+ if (connections === 0) await markBoardIdle(env.DB, room); // your code
265
+ },
266
+ });
267
+ ```
268
+
269
+ | Option | Default | Range |
270
+ | --- | --- | --- |
271
+ | `maxConnections` | 1000 | 1 to 32 768 |
272
+ | `maxConnectionsPerIdentity` | 5 (or `maxConnections` if smaller) | 1 to `maxConnections` |
273
+ | `maxEventBytes` | 16 384 | 256 to 1 048 576 |
274
+ | `maxConnectionAgeSeconds` | 3600 | 1 to 604 800 |
275
+
276
+ Options are checked when `defineRoom` runs; a bad value throws a `TypeError`.
277
+
278
+ - **Caps** count every socket the room still holds, open or closing: a client that never
279
+ answers a close frame keeps its slot until its connection ends, so it cannot pile up sockets.
280
+ `count()` and the hooks' `connections` count open sockets only, so they can be lower than
281
+ what the caps see.
282
+ - **Age**: each socket gets a random age between 90 % and 100 % of
283
+ `maxConnectionAgeSeconds` (never more), so sockets opened together do not expire together.
284
+ - **`onConnect`** runs after the socket is accepted and before the 101 response is returned,
285
+ so keep it short. It is not a gate: authorize in the route.
286
+ - **`onDisconnect`** runs once per socket, when its close completes. A client that never
287
+ answers the close frame delays it until its connection ends. `connectedAt` (a `Date`) tells
288
+ how long the connection lasted; `channels` is a frozen copy of its channels.
289
+ - **`identityConnections`**, in both hooks, is the open connections of the hook's identity
290
+ after the change: 1 in `onConnect` is its first connection in the room, 0 in `onDisconnect`
291
+ means its last one closed. The same id under another `kind` is counted apart.
292
+ - A hook that throws is logged (hook name and error name only: no identity, no message) and
293
+ never reaches clients or breaks the room.
294
+
295
+ ## Publishing
296
+
297
+ `realtime(env.BOARD_ROOMS)` is synchronous and does no I/O, so it is safe in the adapters
298
+ factory; it throws right away (with the Wrangler fix) when the value is not a Durable Object
299
+ namespace. Business logic depends on the `RealtimePublisher` type, not on the binding.
300
+
301
+ - `publish(room, event)` sends the event to every connection on `event.channel` and resolves
302
+ with `{ delivered }` (0 when nobody is connected). Arguments are validated before any call to
303
+ the room; an invalid event, or one larger than the room's `maxEventBytes`, is a `TypeError`.
304
+ - `count(room)` resolves with the open connections (expired ones are closed first and not
305
+ counted).
306
+ - `disconnect(room, { id, kind })` closes that identity's open connections in the room with
307
+ 4001, drops its pending tickets, refuses its connects (and tickets) there for 60 seconds, and
308
+ resolves with `{ closed }`.
309
+ - `presence(room, options?)` lists who is connected (see [Presence](#presence)).
310
+
311
+ Names and events:
312
+
313
+ - Room and channel: `^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$`. 1 to 8 channels per connection, no
314
+ repeats.
315
+ - Event `type`: `^[a-z0-9][a-z0-9._:-]{0,63}$`, e.g. `"card.created"`.
316
+ - Event `data`: optional, JSON only (no `undefined`, functions, non-finite numbers, cycles or
317
+ class instances). Keep it to ids: the client reloads the record.
318
+ - Identity id: 1 to 128 characters (UTF-16 code units), well-formed (no lone surrogates), no
319
+ control characters. The same id with another `kind` is another identity. The room never
320
+ puts the id in a tag or a storage key: it uses a SHA-256 of `kind:id`.
321
+
322
+ Frame sent to clients: `{"channel":"cards","type":"card.created","data":{"id":"…"}}` (`data`
323
+ omitted when absent).
324
+
325
+ ## Presence
326
+
327
+ `presence(room, options?)` tells the server who is connected to a room right now, since when,
328
+ and when each connection last answered a heartbeat. It reads what the room already holds (each
329
+ socket's attachment and the runtime's timestamp of its last auto-answered `"ping"`), so it
330
+ stores nothing and costs nothing while the room hibernates.
331
+
332
+ ```ts
333
+ // In a route of the boards module, after the membership check:
334
+ const { connections, total } = await c.var.adapters.live.presence(`board:${boardId}`, {
335
+ activeWithinSeconds: 60, // the browser client pings every 25 s
336
+ limit: 1000, // connections, not people: one user may hold several
337
+ });
338
+ // People only (services connect too, and one may share an id with a user), each once.
339
+ const online = [
340
+ ...new Set(
341
+ connections
342
+ .filter((connection) => connection.identity.kind === "user")
343
+ .map((connection) => connection.identity.id),
344
+ ),
345
+ ];
346
+ // More matches than `limit`: the list was cut, so show "1000+" rather than claim it is everyone.
347
+ const complete = total === connections.length;
348
+ ```
349
+
350
+ ```ts
351
+ async function isOnline(live: RealtimePublisher, room: string, userId: string) {
352
+ const { total } = await live.presence(room, {
353
+ identity: { id: userId, kind: "user" },
354
+ activeWithinSeconds: 60,
355
+ limit: 1,
356
+ });
357
+ return total > 0;
358
+ }
359
+ ```
360
+
361
+ `isOnline` answers a yes/no about any id it is given, so a route built on it can be used as a
362
+ probe. The route must authorize both the room (the caller is a member of the board) and the
363
+ caller's right to see that specific identity (for example, the target is a member of the same
364
+ board, or one of the caller's contacts). Never take the target id from the client without that
365
+ check. Join and leave signals (below) reveal timing as well: whoever receives them learns when
366
+ people come and go.
367
+
368
+ It resolves with `{ connections, total }`:
369
+
370
+ - `connections`: open connections, oldest `connectedAt` first, each
371
+ `{ identity: { id, kind }, channels, connectedAt, lastSeenAt }` (dates are `Date`; everything
372
+ is frozen). `lastSeenAt` is the last `"ping"` the room answered, or `connectedAt` when there was
373
+ none yet.
374
+ - `total`: how many matched before `limit`, so you know when the list was cut.
375
+
376
+ | Option | Default | Range | Effect |
377
+ | --- | --- | --- | --- |
378
+ | `identity` | none | `{ id, kind }` | only that identity's connections |
379
+ | `channel` | none | a channel name | only connections on that channel |
380
+ | `activeWithinSeconds` | none | 1 to 86 400 | only connections seen in the last N seconds |
381
+ | `limit` | 100 | 1 to 1000 | at most this many connections |
382
+
383
+ `identity` and `channel` together give their intersection. Arguments are validated before the
384
+ call (a `TypeError` that never includes the values) and again by the room. Expired connections
385
+ are closed first and not listed, like `count`; closing sockets are not listed either, nor a
386
+ socket whose stored data cannot be read back.
387
+
388
+ Cost: `identity` narrows the listing to that identity's sockets (through its tag), at most
389
+ `maxConnectionsPerIdentity`; `channel` to that channel's. Before listing, the room runs its lazy
390
+ expiry, which skips work while no socket can have expired yet but sweeps every socket once after
391
+ the room wakes up or when one may have expired. So a narrow query is usually small, and any query
392
+ is bounded by the room's `maxConnections`.
393
+
394
+ - **"Online" is your filter.** The room keeps no online flag: `activeWithinSeconds` decides.
395
+ The browser client pings every `pingIntervalMs` (25 s by default), so 60 tolerates one lost
396
+ ping. A dead connection stays listed, with an old `lastSeenAt`, until the runtime drops it
397
+ (the room has no timer), so filter with `activeWithinSeconds` when it matters.
398
+ - **Verified on Cloudflare** (2026-11-19, a deployed project generated from the starter): a
399
+ `"ping"` answered while the room hibernates moves `lastSeenAt`, and a connection that stops
400
+ pinging drops out of an `activeWithinSeconds` window.
401
+ - **Other clients must ping.** A client that does not use `@cardonjs/realtime-do/client` must
402
+ send the text `"ping"` regularly to count as active; any other message closes the socket
403
+ (1008).
404
+ - **Authorize first; minimize ids and timestamps.** Presence returns identity ids, and
405
+ `connectedAt` / `lastSeenAt` are activity data (when someone is around). It is reachable only
406
+ through the binding, but a route that exposes it must authorize the caller (above: the
407
+ membership check), and should not send other people's ids or times to clients without a
408
+ reason. Often a count or a yes/no (`isOnline`) is enough; when times are needed, coarsen them
409
+ (e.g. "online", "seen in the last hour").
410
+ - One room per query; for several rooms, query each.
411
+
412
+ The framework broadcasts nothing about presence. To tell clients that someone joined or left,
413
+ publish from the hooks when an identity's presence actually changes; a signal without ids is
414
+ enough, and clients reload through your authorized route:
415
+
416
+ ```ts
417
+ const presenceChanged = (env: Bindings, room: string) =>
418
+ realtime(env.BOARD_ROOMS)
419
+ .publish(room, { channel: "presence", type: "presence.changed" })
420
+ .catch(() => undefined); // a failed signal must not break the room
421
+
422
+ export const BoardRoom = defineRoom<Bindings>({
423
+ // Only when the identity's presence changes: its first connection, and after its last one.
424
+ // A second tab, or a reconnect while the old socket is still open, signals nothing.
425
+ onConnect: async ({ room, identityConnections, env }) => {
426
+ if (identityConnections === 1) await presenceChanged(env, room);
427
+ },
428
+ onDisconnect: async ({ room, identityConnections, env }) => {
429
+ if (identityConnections === 0) await presenceChanged(env, room);
430
+ },
431
+ });
432
+ ```
433
+
434
+ Connections that should see the signal join the `presence` channel in `connectToRoom`.
435
+ `onConnect` runs before the 101 response, so the publish adds to the connect's latency.
436
+ `identityConnections` counts the identity's open connections after the change (closing sockets
437
+ are not counted, as with `connections`).
438
+
439
+ Each signal makes every listening client call your route: with N clients, one join is N
440
+ requests and N `presence` calls on the same room, which handles one request at a time. A member
441
+ that loops connect and close, or a phone reconnecting on a flaky network, still signals on every
442
+ round; the connect route's rate limit (20 connects a minute per user, above) is what bounds that
443
+ churn. Keep the rest cheap:
444
+
445
+ - **Coalesce on the client.** Wait a few seconds, with jitter, before reloading, and reload once
446
+ per burst (example below), so clients do not all ask at the same moment.
447
+ - **Rate limit the presence route** per user, like the connect route. It may also cache its
448
+ answer per room for a few seconds (after the authorization check, keyed by room, and only
449
+ when the answer is the same for every caller allowed to see it).
450
+ - **Prefer narrow queries**: `identity` (a yes/no) or `total` with a small `limit`, rather than
451
+ listing the whole room.
452
+
453
+ ```ts
454
+ let pending: ReturnType<typeof setTimeout> | undefined;
455
+ const presenceClient = createRealtimeClient({
456
+ url: `/v1/boards/${boardId}/live`,
457
+ onEvent: (event) => {
458
+ if (event.type !== "presence.changed" || pending !== undefined) return;
459
+ // One reload per burst, 2 to 5 seconds later, spread across clients.
460
+ pending = setTimeout(
461
+ () => {
462
+ pending = undefined;
463
+ void reloadOnline(boardId);
464
+ },
465
+ 2000 + Math.random() * 3000,
466
+ );
467
+ },
468
+ onResync: () => reloadOnline(boardId),
469
+ });
470
+ ```
471
+
472
+ ## Browser client
473
+
474
+ ```ts
475
+ import { createRealtimeClient } from "@cardonjs/realtime-do/client";
476
+
477
+ const client = createRealtimeClient({
478
+ url: `/v1/boards/${boardId}/live`, // same-site: the session cookie goes with the upgrade
479
+ onEvent: (event) => {
480
+ if (event.channel === "cards") void reloadCards(boardId);
481
+ },
482
+ // Called on every reconnect and on each fallback poll while disconnected.
483
+ onResync: () => reloadBoard(boardId),
484
+ onStatus: (status) => showConnectionStatus(status),
485
+ });
486
+
487
+ // When leaving the page:
488
+ client.close();
489
+ ```
490
+
491
+ - A path is resolved against `location` (`https:` → `wss:`). `wss:` is required, except from
492
+ an `http:` page on a local development host (`localhost`, `*.localhost`, `127.0.0.1`,
493
+ `[::1]`) to a local host.
494
+ - Statuses: `"connecting"` → `"open"`; `"reconnecting"` while waiting to reconnect;
495
+ `"closed"` after `close()` or a protocol violation.
496
+ - Reconnects with exponential backoff and full jitter between `minBackoffMs` (1000) and
497
+ `maxBackoffMs` (30 000); the attempt counter resets after a connection stays open for 10 s.
498
+ - Sends `"ping"` every `pingIntervalMs` (25 000); without `"pong"` within `pongTimeoutMs`
499
+ (10 000) it closes the socket and reconnects. The room answers pings without waking up, and
500
+ each answered ping is what `presence` reports as `lastSeenAt`.
501
+ - While disconnected, calls `onResync` every `pollIntervalMs` (30 000; 0 disables it).
502
+ - Frames that are not well-formed events are dropped. Errors thrown (or rejections) from
503
+ `onEvent`, `onResync` and `onStatus` never break the client.
504
+ - `close()` stops the socket and every timer and reports `"closed"`; after it returns no
505
+ callback fires, also when it is called from inside `onEvent`, `onResync` or `onStatus`.
506
+ - **Stop on 401/403.** The client cannot tell a revoked session from a network failure. If
507
+ `onResync` gets a 401 or 403 from your API, call `client.close()` (and send the user to sign
508
+ in); otherwise the client keeps retrying with backoff.
509
+ - **No tokens in the URL.** Do not put a session token or API key in the socket URL's query
510
+ string: URLs end up in logs and history. The upgrade is authenticated by the same-site
511
+ session cookie, or by a one-time ticket offered as a subprotocol (next section).
512
+
513
+ ## Clients without a cookie: tickets
514
+
515
+ A browser cannot set `Authorization` on a WebSocket upgrade, and a credential never goes in a
516
+ URL. A caller whose credential travels in a header (an access token of
517
+ `@cardonjs/access-tokens`, a bearer of another site) exchanges it for a one-time ticket, then
518
+ opens the socket offering the ticket as a WebSocket subprotocol, the only header a page can set
519
+ on an upgrade.
520
+
521
+ The example: a guest who placed an order holds an access token for it (see
522
+ `@cardonjs/access-tokens`) and follows the order live on a shop page of another site. The room
523
+ is per order (`order:<id>`).
524
+
525
+ ```ts
526
+ import { requireAccessToken } from "@cardonjs/access-tokens";
527
+ import { requireAuth } from "@cardonjs/auth";
528
+ import {
529
+ type CardonEnv,
530
+ createApp,
531
+ defineModule,
532
+ errorEnvelopeSchema,
533
+ idSchema,
534
+ ok,
535
+ rateLimit,
536
+ rateLimitKeys,
537
+ successEnvelope,
538
+ UnauthorizedError,
539
+ workersRateLimiter,
540
+ } from "@cardonjs/core";
541
+ import {
542
+ connectToRoomWithTicket,
543
+ defineRoom,
544
+ issueRoomTicket,
545
+ realtime,
546
+ } from "@cardonjs/realtime-do";
547
+ import { createRoute, z } from "@hono/zod-openapi";
548
+
549
+ const SHOP_ORIGIN = "https://shop.example.com"; // the page that opens the socket
550
+
551
+ type Bindings = { ORDER_ROOMS: DurableObjectNamespace; LIVE_LIMITER: RateLimit; DB: D1Database };
552
+ const adapters = (env: Bindings) => ({
553
+ auth: sessionAuth(env), // your Authenticator, for the routes that need a login
554
+ tokens: orderTokens(env.DB), // accessTokens({ store, prefix: "ord", ... })
555
+ live: realtime(env.ORDER_ROOMS),
556
+ limiter: workersRateLimiter(env.LIVE_LIMITER, { periodSeconds: 60 }),
557
+ });
558
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
559
+
560
+ const errors = (description: string) => ({
561
+ description,
562
+ content: { "application/json": { schema: errorEnvelopeSchema } },
563
+ });
564
+ const perIp = rateLimit<AppEnv>({
565
+ name: "order-live",
566
+ limiter: (c) => c.var.adapters.limiter,
567
+ key: rateLimitKeys.ip,
568
+ });
569
+ const orderParams = z.object({ id: idSchema });
570
+
571
+ // 1. Exchange: the access token (in `Authorization`) for a ticket to this order's room.
572
+ const ticketRoute = createRoute({
573
+ method: "post",
574
+ path: "/{id}/live-ticket",
575
+ tags: ["Orders"],
576
+ summary: "Get a one-time ticket for the order's live updates",
577
+ middleware: [
578
+ perIp,
579
+ requireAccessToken<AppEnv>((c) => c.var.adapters.tokens, {
580
+ resource: { type: "order", param: "id" },
581
+ scope: "order:read",
582
+ }),
583
+ ] as const,
584
+ request: { params: orderParams },
585
+ responses: {
586
+ 200: {
587
+ description: "The ticket, usable once within `expiresAt`",
588
+ content: {
589
+ "application/json": {
590
+ schema: successEnvelope(z.object({ ticket: z.string(), expiresAt: z.string() })),
591
+ },
592
+ },
593
+ },
594
+ 429: errors("Too many requests, or too many pending tickets"),
595
+ },
596
+ });
597
+
598
+ // 2. Connect: the ticket is the authorization (public in `requireAuth`).
599
+ const liveRoute = createRoute({
600
+ method: "get",
601
+ path: "/{id}/live",
602
+ tags: ["Orders"],
603
+ summary: "Open the order's live updates with a ticket (WebSocket upgrade)",
604
+ middleware: perIp,
605
+ request: { params: orderParams },
606
+ responses: {
607
+ 101: { description: "Switching to the WebSocket protocol" },
608
+ 400: errors("Not a WebSocket upgrade"),
609
+ 401: errors("No valid ticket for this order"),
610
+ 403: errors("Origin not allowed"),
611
+ 429: errors("Too many connects, or too many connections"),
612
+ },
613
+ });
614
+
615
+ const ordersLive = defineModule<AppEnv>({
616
+ name: "orders-live",
617
+ prefix: "/v1/orders",
618
+ routes: (app) => {
619
+ app.openapi(ticketRoute, async (c) => {
620
+ const grant = c.var.accessToken;
621
+ if (grant === undefined) throw new UnauthorizedError(); // fail closed
622
+ const { ticket, expiresAt } = await issueRoomTicket(
623
+ c.env.ORDER_ROOMS,
624
+ `order:${grant.resourceId}`, // from the grant: the token is for this order
625
+ {
626
+ identity: { id: grant.id, kind: "guest" }, // the token's record id
627
+ channels: ["order"], // chosen by the server
628
+ connectionExpiresAt: grant.expiresAt, // the socket does not outlive the token
629
+ },
630
+ );
631
+ c.header("Cache-Control", "no-store"); // a credential: never cached
632
+ return ok(c, { ticket, expiresAt: expiresAt.toISOString() });
633
+ });
634
+
635
+ app.openapi(liveRoute, async (c) => {
636
+ const { id } = c.req.valid("param");
637
+ return connectToRoomWithTicket(c.env.ORDER_ROOMS, `order:${id}`, c.req.raw, {
638
+ allowedOrigins: [SHOP_ORIGIN],
639
+ });
640
+ });
641
+ },
642
+ });
643
+
644
+ const app = createApp(adapters, {
645
+ cors: { origins: [SHOP_ORIGIN] }, // the exchange is a cross-origin fetch from the shop page
646
+ guard: requireAuth<AppEnv>({
647
+ authenticator: (c) => c.var.adapters.auth,
648
+ public: ["POST /v1/orders/:id/live-ticket", "GET /v1/orders/:id/live"],
649
+ }),
650
+ }).register(ordersLive);
651
+
652
+ export const OrderRoom = defineRoom<Bindings>();
653
+
654
+ export default app;
655
+ ```
656
+
657
+ On the shop page, the client asks for a new ticket before every connection attempt:
658
+
659
+ ```ts
660
+ import { createRealtimeClient } from "@cardonjs/realtime-do/client";
661
+
662
+ const client = createRealtimeClient({
663
+ url: `https://api.example.com/v1/orders/${orderId}/live`,
664
+ ticket: async () => {
665
+ const res = await fetch(`https://api.example.com/v1/orders/${orderId}/live-ticket`, {
666
+ method: "POST",
667
+ headers: { Authorization: `Bearer ${orderToken}` },
668
+ });
669
+ if (res.status === 401) client.close(); // the token expired or was revoked: stop
670
+ if (!res.ok) throw new Error(`live ticket: ${res.status}`); // a failed attempt: backoff
671
+ return ((await res.json()) as { data: { ticket: string } }).data.ticket;
672
+ },
673
+ onEvent: () => void reloadOrder(orderId),
674
+ onResync: () => reloadOrder(orderId),
675
+ });
676
+ ```
677
+
678
+ The `ticket` function is first called while `createRealtimeClient` runs, before `client` is
679
+ assigned: it must not use `client` before its first `await` (the `close()` above runs after one).
680
+ An attempt whose ticket does not come within 10 seconds has failed: the client backs off and
681
+ tries again with a new call, and a late answer opens nothing.
682
+
683
+ How it works:
684
+
685
+ - **The room keeps the tickets.** `issueRoomTicket` asks the room (through the binding) for a
686
+ ticket: `crt_` and 43 characters (32 random bytes). The room stores only its SHA-256, with the
687
+ identity, the channels and the expiry, and answers the ticket once. No secret, table or new
688
+ binding. A ticket exists only in the room that issued it, so it opens that room and no other.
689
+ - **Single use.** `connectToRoomWithTicket` sends the ticket to the room, which reads and deletes
690
+ its entry in one synchronous step: of two connects with one ticket, exactly one finds it. The
691
+ room then connects exactly as `connectToRoom` does, with the stored identity and channels
692
+ (same caps, revocation window and hooks). The ticket is used up even when that connect is
693
+ refused (429): the client gets a new one for its next attempt.
694
+ - **On the wire.** The client offers `Sec-WebSocket-Protocol: cardon.ticket.v1, <ticket>`,
695
+ exactly these two entries in this order, and the 101 selects `cardon.ticket.v1` (a browser
696
+ fails a connection that offered subprotocols and got none). Never in the query string.
697
+ - **Lifetimes.** `ttlSeconds` (default 30, 5 to 120) is how long the ticket can be used.
698
+ `connectionExpiresAt` (optional, a `Date`) is when the credential that was exchanged expires:
699
+ the ticket never outlives it, and the socket is closed with 4000 at the room's first sweep after
700
+ it (connect, publish, count or presence), if that is earlier than its age from
701
+ `maxConnectionAgeSeconds`; it never extends that age. The client then asks for a new ticket,
702
+ which the exchange route refuses once the token expired.
703
+ - **Caps.** At most 1000 pending tickets per room and 5 per identity; past that, issuing answers
704
+ `RateLimitedError` (429). Used tickets free their slot at once, expired ones when the room next
705
+ issues a ticket (they are deleted then; there is no alarm). In a room many identities share,
706
+ the room-wide cap can be filled by many credentials together (each within its own 5), which
707
+ blocks issuing for everyone there until tickets are used or expire: rate limit the exchange
708
+ route per credential as well as per IP (for example a second `rateLimit` after
709
+ `requireAccessToken`, keyed on `c.var.accessToken?.id`). The caps are not configurable.
710
+ - **Revocation.** `disconnect(room, { id, kind: "guest" })` closes the identity's sockets, drops
711
+ its pending tickets and, for 60 seconds, refuses its tickets and connects (429). A socket that
712
+ is already open otherwise stays open until `connectionExpiresAt`, its maximum age or
713
+ `disconnect`, so an app that revokes a token also calls `disconnect`:
714
+
715
+ ```ts
716
+ await tokens.revoke(record.id);
717
+ await live.disconnect(`order:${orderId}`, { id: record.id, kind: "guest" });
718
+ ```
719
+
720
+ `issueRoomTicket` throws a `TypeError` for invalid arguments (room, identity, channels,
721
+ `ttlSeconds`, a `connectionExpiresAt` that is not a `Date` later than now, binding), before
722
+ calling the room, and `RateLimitedError` over the caps or during a revocation window. `connectToRoomWithTicket`
723
+ throws the core errors:
724
+
725
+ | Case | Error |
726
+ | --- | --- |
727
+ | Not a `GET` with `Upgrade: websocket` | `ValidationError` (400) |
728
+ | `Origin` missing or not exactly in `allowedOrigins` | `ForbiddenError` (403) |
729
+ | No ticket, malformed, unknown, used, expired, for another room, or other subprotocol entries | `UnauthorizedError` (401), one message for all |
730
+ | Room full, the identity has too many connections, or it was disconnected less than 60 s ago | `RateLimitedError` (429) |
731
+
732
+ What stays the app's:
733
+
734
+ - The exchange route's authentication and its authorization of the room (above:
735
+ `requireAccessToken` for that order, with the room built from the grant), its rate limit, and
736
+ `Cache-Control: no-store` on its answer.
737
+ - **A rate limit on the connect route, per IP: required.** The route is public and takes the
738
+ room name from the path, so without a credential anyone can make it wake a Durable Object for
739
+ any room name. The per-IP `rateLimit` above bounds that; the route may also check that the room
740
+ is one the app has (the order exists) before calling `connectToRoomWithTicket`.
741
+ - The `Origin` check: `allowedOrigins` holds the pages allowed to open the socket.
742
+ - A room class created with `new_sqlite_classes` (above). On another backend a ticket connect is
743
+ an `Error`, so the client gets the app's generic 500, and the log says why.
744
+
745
+ The package's own code never puts the ticket in a URL, a log line, an error message, a socket
746
+ tag or storage (only its hash is stored). The ticket does travel in the `Sec-WebSocket-Protocol`
747
+ request header of the connect route: an app that records request headers (its own logging
748
+ middleware, a Tail Worker, a log push) must redact that header, and keep the exchange route's
749
+ answer out of its logs.
750
+
751
+ `"guest"` is a `RoomIdentity.kind` for a caller without an account; with an access token, `id`
752
+ is the token's record id (`grant.id`), so `disconnect` with it closes that token's sockets.
753
+ Presence lists guests like any identity: filter by `kind` when it matters.
754
+
755
+ ## Limits and close codes
756
+
757
+ | Close code | Meaning | Client |
758
+ | --- | --- | --- |
759
+ | 1008 | Protocol violation: the client sent something other than `"ping"` | stops (`"closed"`) |
760
+ | 4000 | Connection past its age (see `maxConnectionAgeSeconds`), or past the `connectionExpiresAt` of its ticket: authenticate again | reconnects after a random delay below `minBackoffMs` |
761
+ | 4001 | Disconnected by the server (`disconnect`) | reconnects with backoff; the route decides |
762
+
763
+ Connection age is checked lazily (there is no alarm): an expired socket is closed the next time
764
+ the room handles a connect, a publish, a count or a presence query.
765
+
766
+ Cloudflare limits the room is built within (checked against workerd): 10 tags per hibernating
767
+ WebSocket (up to 8 channels plus 1 identity tag of 74 ASCII characters), 256 bytes per tag,
768
+ 16 384 bytes per attachment, 2 048 characters for the auto-response request and response.
769
+
770
+ The room keeps nothing about a connection in instance memory: channels and the hashed identity
771
+ are the socket's tags; the room name, identity, channels, connection time and expiry are its
772
+ attachment; revocation markers are in Durable Object storage. Roles and email are not stored
773
+ (they would go stale). The runtime can evict an idle room while its sockets stay open; the
774
+ next event builds a new instance that finds them again.
775
+
776
+ ## Testing (`@cardonjs/realtime-do/testing`)
777
+
778
+ ```ts
779
+ import { memoryRealtime } from "@cardonjs/realtime-do/testing";
780
+
781
+ const live = memoryRealtime();
782
+ // ...run a route with `live` as the `live` adapter, then:
783
+ expect(live.published).toEqual([
784
+ { room: `board:${boardId}`, event: { channel: "cards", type: "card.created", data: { id } } },
785
+ ]);
786
+ ```
787
+
788
+ `memoryRealtime()` validates with the same rules and records `published`, `disconnected`
789
+ (`{ room, identity: { id, kind } }`) and `presenceQueries` (`{ room, query }`, the validated
790
+ query with `limit` filled in), so a test can check that a forbidden path never asked for
791
+ presence, or that a route scoped its query (`identity`, `limit`); `clear()` empties them.
792
+ There are no connections: `count(room)` and `publish`'s `delivered` return what `setCount(room,
793
+ n)` set (default 0). `presence(room, options)` lists what `setPresence(room, connections)` set
794
+ (`{ identity, channels, connectedAt, lastSeenAt? }[]`, `lastSeenAt` defaulting to `connectedAt`;
795
+ times after `Date.now()` are a `TypeError`, as the room never reports them), with the room's
796
+ filters, order and limit; `activeWithinSeconds` is measured against `Date.now()`,
797
+ so fake timers apply. Test-only.
798
+
799
+ ## Not covered
800
+
801
+ - A ticket in the query string, for clients that cannot offer subprotocols.
802
+ - Client → server messages (other than the keep-alive ping), message history or replay,
803
+ subscriptions after connect, binary frames, alarms.
804
+ - Presence broadcast by the framework, presence across rooms in one query, custom
805
+ per-connection metadata, and closing idle connections on a timer.