@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/llms.txt ADDED
@@ -0,0 +1,233 @@
1
+ # @cardonjs/realtime-do
2
+
3
+ Real-time for Cardón apps on Cloudflare Durable Objects. A room (one Durable Object) holds
4
+ hibernating WebSockets; the API publishes small events to it after saving data; a reconnecting
5
+ browser client receives them and reloads what changed. Events flow server to client only and carry
6
+ a hint (ids), never the record: the database stays the source of truth. The main entry runs on
7
+ Cloudflare Workers only (it needs a Durable Object namespace binding). `./client` has zero
8
+ dependencies and runs in browsers. `./testing` is an in-memory fake with no runtime requirements.
9
+
10
+ Full documentation: README.md in this package.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @cardonjs/realtime-do @cardonjs/core
16
+ ```
17
+
18
+ `@cardonjs/core` is the only peer dependency. The types `DurableObjectNamespace` and
19
+ `DurableObjectState` come from `@cloudflare/workers-types` (as in
20
+ `@cardonjs/config/tsconfig.workers.json`). The client needs only the DOM types. Wrangler: bind the
21
+ room class under `[[durable_objects.bindings]]` and create it with a `new_sqlite_classes` migration
22
+ (tickets need the SQLite backend; everything else also works on a `new_classes` room).
23
+
24
+ ## Exports
25
+
26
+ ### `@cardonjs/realtime-do`
27
+ - `defineRoom<Env>(options?: RoomOptions<Env>): RoomClass<Env>`: returns the Durable Object class
28
+ to export from the Worker entry under the Wrangler `class_name`. Options (checked when it runs,
29
+ a bad value throws `TypeError`): `maxConnections` (default 1000, 1 to 32 768),
30
+ `maxConnectionsPerIdentity` (default 5, or `maxConnections` if smaller; 1 to `maxConnections`),
31
+ `maxEventBytes` (default 16 384, 256 to 1 048 576), `maxConnectionAgeSeconds` (default 3600,
32
+ 1 to 604 800), hooks `onConnect` and `onDisconnect`, which get
33
+ `{ room, identity, channels, connectedAt, connections, identityConnections, env }` (`channels`
34
+ frozen, `connectedAt` a `Date`; `connections` and `identityConnections` are the room's and this
35
+ identity's open connections after the change: `identityConnections` 1 in `onConnect` is its
36
+ first connection, 0 in `onDisconnect` means its last one closed).
37
+ - `connectToRoom(namespace, room, request, options: ConnectOptions): Promise<Response>`: opens a
38
+ socket from a route and resolves with the 101 response to return. `options` is
39
+ `{ identity, channels, allowedOrigins }`, all required. Throws `ValidationError` (400) when the
40
+ request is not a `GET` with `Upgrade: websocket`, `ForbiddenError` (403) when `Origin` is missing
41
+ or not exactly in `allowedOrigins`, `RateLimitedError` (429) when the room is full, the identity
42
+ has too many connections, or it was disconnected less than 60 s ago. Invalid arguments throw
43
+ `TypeError`.
44
+ - `issueRoomTicket(namespace, room, options: RoomTicketOptions): Promise<RoomTicket>`: for a
45
+ client without a same-site cookie (an access token holder). Call it from an exchange route that
46
+ authenticated the caller and authorized the room. `options` is `{ identity, channels,
47
+ ttlSeconds?, connectionExpiresAt? }` (`ttlSeconds` default 30, 5 to 120; `connectionExpiresAt` a
48
+ `Date` later than now, the exchanged credential's expiry). Resolves with frozen
49
+ `{ ticket, expiresAt: Date }`: `ticket` is `crt_` + 43 base64url characters, single-use, bound to that room, identity and
50
+ channels, never after `connectionExpiresAt`. The room stores only its SHA-256. Throws
51
+ `RateLimitedError` (429) over 1000 pending tickets per room or 5 per identity, or within 60 s of
52
+ `disconnect` of the identity; invalid arguments throw `TypeError` before calling the room; a room
53
+ class that is not SQLite-backed throws an `Error` saying so.
54
+ - `connectToRoomWithTicket(namespace, room, request, options: TicketConnectOptions):
55
+ Promise<Response>`: the connect route for tickets, public in `requireAuth` (the ticket is its
56
+ authorization). `options` is `{ allowedOrigins }`. The client offers `Sec-WebSocket-Protocol:
57
+ cardon.ticket.v1, <ticket>` (exactly these two entries, in this order); the 101 selects
58
+ `cardon.ticket.v1`. The room consumes the ticket (read and delete in one synchronous step), then
59
+ connects as `connectToRoom` does with the stored identity and channels; the socket closes with
60
+ 4000 from `connectionExpiresAt` if earlier than its age. Throws `ValidationError` (400) for a
61
+ non-upgrade, `ForbiddenError` (403) for the origin, `UnauthorizedError` (401, one message for
62
+ every ticket failure: missing, malformed, unknown, used, expired, another room, other
63
+ subprotocol entries), `RateLimitedError` (429) as `connectToRoom` (the ticket is used up all the
64
+ same), and an `Error` (the app's 500) on a room class that is not SQLite-backed.
65
+ - `realtime(namespace: DurableObjectNamespace): RealtimePublisher`: synchronous, no I/O; throws
66
+ right away when the value is not a Durable Object namespace. The publisher has
67
+ `publish(room, event): Promise<{ delivered: number }>` (0 when nobody is connected),
68
+ `count(room): Promise<number>` (open connections) and
69
+ `disconnect(room, { id, kind }): Promise<{ closed: number }>` (closes that identity's sockets in
70
+ the room with 4001, drops its pending tickets, and refuses its connects and tickets there for
71
+ 60 seconds) and
72
+ `presence(room, options?: PresenceOptions): Promise<Presence>`: open connections, oldest first,
73
+ as frozen `{ identity: { id, kind }, channels, connectedAt: Date, lastSeenAt: Date }`
74
+ (`lastSeenAt`: last answered `"ping"`, else `connectedAt`) plus `total` (matches before
75
+ `limit`). Options: `identity`, `channel` (both: intersection), `activeWithinSeconds` (1 to
76
+ 86 400), `limit` (default 100, 1 to 1000; it counts connections, not people). Expired and
77
+ closing sockets are not listed. `identity` narrows the listing to that identity's sockets, but
78
+ the lazy expiry that runs first may sweep every socket after a wake-up: any query is bounded by
79
+ `maxConnections`, not free.
80
+ - `validEvent(event: unknown, maxEventBytes = 16_384): RealtimeEvent`: returns a frozen, validated
81
+ copy (only `channel`, `type`, `data`); throws `TypeError` when invalid or too large.
82
+ - `assertValidRoom(room: unknown)`, `assertValidChannel(channel: unknown)`: assert a valid name,
83
+ else `TypeError`.
84
+ - `assertValidChannels(channels: unknown)`: asserts 1 to 8 valid channel names without repeats.
85
+ - Types: `ConnectOptions`, `RoomIdentity` (`{ id: string; kind: "user" | "service" | "guest" }`;
86
+ `"guest"`: a caller without an account, e.g. an access token whose record id is `id`),
87
+ `RoomTicketOptions`, `RoomTicket`, `TicketConnectOptions`,
88
+ `RealtimePublisher`, `Presence`, `PresenceConnection`, `PresenceOptions`, `RoomClass`,
89
+ `RoomHookContext`, `RoomOptions`, `JsonValue`,
90
+ `RealtimeEvent` (`{ channel: string; type: string; data?: JsonValue }`).
91
+
92
+ ### `@cardonjs/realtime-do/client`
93
+ - `createRealtimeClient(options: RealtimeClientOptions): RealtimeClient`: reconnecting browser
94
+ client. Required: `url` (`wss://…`, or a path resolved against `location`), `onEvent(event)`,
95
+ `onResync()` (called on every reconnect and on each fallback poll while disconnected). Optional:
96
+ `onStatus(status)`, `pollIntervalMs` (30 000; 0 disables polling), `pingIntervalMs` (25 000),
97
+ `pongTimeoutMs` (10 000), `minBackoffMs` (1000), `maxBackoffMs` (30 000), `ticket` (a function
98
+ `() => string | Promise<string>` called before every connection attempt; its ticket is offered
99
+ as `new WebSocket(url, ["cardon.ticket.v1", ticket])`; a rejection or a malformed value is a
100
+ failed attempt with backoff; without it the socket is `new WebSocket(url)`), and `WebSocket` and
101
+ `random` (injectable for tests). Returns `{ status, close() }`.
102
+ - Types: `ConnectionStatus` (`"connecting" | "open" | "reconnecting" | "closed"`),
103
+ `RealtimeClientOptions`, `RealtimeClient`, `JsonValue`, `RealtimeEvent`.
104
+
105
+ ### `@cardonjs/realtime-do/testing`
106
+ - `memoryRealtime(options?: MemoryRealtimeOptions): MemoryRealtime`: test-only `RealtimePublisher`
107
+ that validates with the same rules and records calls in `published` (`{ room, event }`) and
108
+ `disconnected` (`{ room, identity: { id, kind } }`) and `presenceQueries` (`{ room, query }`,
109
+ the validated query with `limit` filled in; assert a forbidden path never queried presence, or
110
+ that the query was scoped). There are no connections: `count(room)` and
111
+ `publish`'s `delivered` return what `setCount(room, n)` set (default 0); `disconnect` resolves
112
+ with `{ closed: 0 }`. `presence(room, options?)` lists what
113
+ `setPresence(room, connections: FakeConnection[])` set (`{ identity, channels, connectedAt: Date,
114
+ lastSeenAt?: Date }`; times after `Date.now()` throw `TypeError`), with the room's validation,
115
+ filters, order and limit;
116
+ `activeWithinSeconds` is measured against `Date.now()`. `clear()` forgets the recorded calls,
117
+ counts and connections. Option: `maxEventBytes` (default 16 384).
118
+ - Types: `PublishedEvent`, `DisconnectCall`, `PresenceQueryCall`, `PresenceQuery`,
119
+ `FakeConnection`, `MemoryRealtime`, `MemoryRealtimeOptions`.
120
+
121
+ ## Minimal example
122
+
123
+ ```ts
124
+ import { getIdentity } from "@cardonjs/auth";
125
+ import { type CardonEnv, defineModule, ForbiddenError, idSchema } from "@cardonjs/core";
126
+ import { connectToRoom, defineRoom, realtime } from "@cardonjs/realtime-do";
127
+ import { createRoute, z } from "@hono/zod-openapi";
128
+
129
+ type Bindings = { BOARD_ROOMS: DurableObjectNamespace; APP_ORIGIN: string };
130
+ declare const boards: { isMember(boardId: string, userId: string): Promise<boolean> }; // yours
131
+
132
+ export const adapters = (env: Bindings) => ({ boards, live: realtime(env.BOARD_ROOMS) });
133
+ type AppEnv = CardonEnv<Bindings, ReturnType<typeof adapters>>;
134
+
135
+ const liveRoute = createRoute({
136
+ method: "get",
137
+ path: "/{boardId}/live",
138
+ tags: ["Boards"],
139
+ summary: "Open the board's live updates (WebSocket upgrade)",
140
+ request: { params: z.object({ boardId: idSchema }) },
141
+ responses: { 101: { description: "Switching to the WebSocket protocol" } },
142
+ });
143
+
144
+ export const boardsModule = defineModule<AppEnv>({
145
+ name: "boards",
146
+ prefix: "/v1/boards",
147
+ routes: (app) => {
148
+ app.openapi(liveRoute, async (c) => {
149
+ const { boardId } = c.req.valid("param");
150
+ const identity = getIdentity(c); // the app's auth guard already ran
151
+ const member = await c.var.adapters.boards.isMember(boardId, identity.id);
152
+ if (!member) throw new ForbiddenError();
153
+ return connectToRoom(c.env.BOARD_ROOMS, `board:${boardId}`, c.req.raw, {
154
+ identity, // only id and kind reach the room
155
+ channels: ["cards"], // chosen by the server, never by the client
156
+ allowedOrigins: [c.env.APP_ORIGIN], // e.g. "https://app.example.com"
157
+ });
158
+ });
159
+ },
160
+ });
161
+
162
+ // The Durable Object class, exported under the `class_name` of the Wrangler config.
163
+ export const BoardRoom = defineRoom<Bindings>();
164
+ ```
165
+
166
+ ## Rules and common mistakes
167
+
168
+ - Authenticate and authorize the room in the route, before `connectToRoom`. `onConnect` is not a
169
+ gate: if it throws, the error is logged and the connection stays.
170
+ - Never forward a client request to the room stub (`stub.fetch(c.req.raw)` or any proxy route): the
171
+ room trusts what it receives, identity included. Only `connectToRoom` and `realtime()` call it.
172
+ - `allowedOrigins` holds exact origins (`https://host[:port]`). An empty list or `"*"` throws;
173
+ `http:` is accepted only for `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`. The check stops
174
+ cross-site WebSocket hijacking (browsers send the cookie on cross-site upgrades).
175
+ - Channels are chosen by the server, never by the client. Room and channel names match
176
+ `^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$`; event `type` matches `^[a-z0-9][a-z0-9._:-]{0,63}$`.
177
+ - Event `data` is optional and JSON only (no `undefined`, functions, non-finite numbers, cycles or
178
+ class instances). Keep it to ids; the client reloads the record through the API.
179
+ - Publish after the data is saved, in `c.executionCtx.waitUntil(...)` with a `.catch`: a failed
180
+ publish must not fail the request. Depend on the `RealtimePublisher` type, not on the binding.
181
+ - Rate limit the connect route per user with core's `rateLimit` (after the guard).
182
+ - After revoking a user's access, call `disconnect(room, { id, kind })`. `maxConnectionAgeSeconds`
183
+ makes clients come back through the route to authenticate again (close code 4000).
184
+ - Client: `wss:` is required except from an `http:` page on a local development host. Do not put a
185
+ session token or API key in the socket URL; the upgrade uses the same-site session cookie, or a
186
+ ticket offered as a subprotocol.
187
+ - Tickets: the exchange route authenticates (e.g. `requireAccessToken`), builds the room name from
188
+ what the credential grants (`order:${grant.resourceId}`), uses `{ id: grant.id, kind: "guest" }`
189
+ and `connectionExpiresAt: grant.expiresAt`, has a rate limit, and answers with
190
+ `Cache-Control: no-store`. Never log the ticket or put it in a URL; it travels in the connect
191
+ request's `Sec-WebSocket-Protocol` header, so redact that header wherever the app records request
192
+ headers. Revoking a token does not close open sockets: also call
193
+ `disconnect(room, { id: grant.id, kind: "guest" })`.
194
+ - The public ticket connect route needs a per-IP `rateLimit` (required: it wakes a Durable Object
195
+ for any room name in the path without a credential); it may check the room exists for the app
196
+ first. Rate limit the exchange route per credential as well as per IP: the 1000 pending tickets
197
+ per room can be filled by many identities together. Caps are not configurable.
198
+ - Client with `ticket`: when the exchange answers 401, call `client.close()` (the credential is
199
+ gone); otherwise throw to retry with backoff. No answer within 10 s is a failed attempt. The
200
+ function is first called inside `createRealtimeClient`: do not use `client` before its first
201
+ `await`.
202
+ - Client: if `onResync` gets a 401 or 403 from your API, call `client.close()`; otherwise it keeps
203
+ retrying with backoff. Call `client.close()` when leaving the page.
204
+ - Presence returns identity ids, and `connectedAt` / `lastSeenAt` are activity data: authorize the
205
+ caller before exposing it in a route, and do not send other people's ids or times to clients
206
+ without a reason (a count or a yes/no is often enough; coarsen times when needed).
207
+ - A yes/no route (`presence(room, { identity, limit: 1 })`) is a probe unless it authorizes both
208
+ the room and the caller's right to see that specific identity; never take the target id from
209
+ the client without that check. Join/leave signals reveal timing too.
210
+ - Listing who is online: keep `kind === "user"` (services connect too and may share an id with a
211
+ user), dedupe per id, and treat `total > connections.length` as a cut list (or set `limit`).
212
+ - "Online" is `activeWithinSeconds`: the browser client pings every 25 s, so 60 is a sensible
213
+ value; a client that does not use `./client` must send the text `"ping"` to count as active.
214
+ - The framework broadcasts nothing about presence. To signal joins and leaves, publish
215
+ `{ channel: "presence", type: "presence.changed" }` (no ids) with `realtime(env.BINDING)` only
216
+ when presence changes: in `onConnect` when `identityConnections === 1`, in `onDisconnect` when
217
+ `identityConnections === 0`. Each signal makes every listening client reload through your
218
+ authorized route, so: clients debounce with jitter (one reload per burst, a few seconds later);
219
+ the presence route is rate limited per user and may cache its answer per room for a few
220
+ seconds; prefer narrow queries (`identity`, `total`). Connect/close churn still signals each
221
+ round: the connect route's rate limit is what bounds it.
222
+ - Close codes: 1008 protocol violation (client sent something other than `"ping"`; client stops),
223
+ 4000 connection past its age or its ticket's `connectionExpiresAt` (client reconnects), 4001
224
+ disconnected by the server.
225
+ - `memoryRealtime()` is test-only: nothing is delivered anywhere.
226
+
227
+ ## Out of scope
228
+
229
+ - A ticket in the query string, for clients that cannot offer subprotocols.
230
+ - Client to server messages other than the keep-alive ping.
231
+ - Message history or replay, subscriptions after connect, binary frames, alarms.
232
+ - Presence broadcast by the framework, presence across rooms in one query, custom per-connection
233
+ metadata, closing idle connections on a timer.
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@cardonjs/realtime-do",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.3.0",
4
+ "description": "Real-time for Cardón apps on Cloudflare Durable Objects: a room with hibernating WebSockets, connect and publish helpers, a reconnecting browser client and an in-memory fake.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cardonjs/cardon.git",
9
+ "directory": "packages/realtime-do"
10
+ },
11
+ "homepage": "https://github.com/cardonjs/cardon/tree/main/packages/realtime-do#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cardonjs/cardon/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./client": {
23
+ "types": "./dist/client.d.ts",
24
+ "default": "./dist/client.js"
25
+ },
26
+ "./testing": {
27
+ "types": "./dist/testing.d.ts",
28
+ "default": "./dist/testing.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "llms.txt"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "peerDependencies": {
39
+ "@cardonjs/core": "^0.5.1"
40
+ },
41
+ "devDependencies": {
42
+ "@cloudflare/workers-types": "5.20261114.1",
43
+ "@hono/zod-openapi": "1.6.3",
44
+ "@scalar/hono-api-reference": "0.12.20",
45
+ "hono": "4.13.18",
46
+ "miniflare": "4.20260730.0",
47
+ "rolldown": "1.2.19",
48
+ "typescript": "7.0.2",
49
+ "vitest": "5.1.0",
50
+ "zod": "4.6.7",
51
+ "@cardonjs/access-tokens": "0.1.4",
52
+ "@cardonjs/config": "0.0.0",
53
+ "@cardonjs/core": "0.5.1",
54
+ "@cardonjs/testing": "0.6.0",
55
+ "@cardonjs/auth": "0.2.6"
56
+ },
57
+ "scripts": {
58
+ "build": "tsc -p tsconfig.build.json",
59
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
60
+ "test": "vitest run"
61
+ }
6
62
  }