@bymax-one/nest-realtime 1.0.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 ADDED
@@ -0,0 +1,671 @@
1
+ <p align="center">
2
+ <img src="https://img.shields.io/badge/%40bymax--one-nest--realtime-000000?style=for-the-badge&logo=nestjs&logoColor=E0234E" alt="@bymax-one/nest-realtime" />
3
+ </p>
4
+
5
+ <h1 align="center">@bymax-one/nest-realtime</h1>
6
+
7
+ <p align="center">
8
+ <strong>Dual-transport realtime for NestJS & React</strong><br />
9
+ <sub>SSE by Default · WebSocket Opt-In · Multi-Tenant Rooms · Auth Inversion · Zero Runtime Dependencies</sub>
10
+ </p>
11
+
12
+ <p align="center">
13
+ <a href="https://www.npmjs.com/package/@bymax-one/nest-realtime"><img src="https://img.shields.io/npm/v/@bymax-one/nest-realtime?style=flat-square&colorA=000000&colorB=000000" alt="npm version" /></a>
14
+ <a href="https://www.npmjs.com/package/@bymax-one/nest-realtime"><img src="https://img.shields.io/npm/dm/@bymax-one/nest-realtime?style=flat-square&colorA=000000&colorB=000000" alt="npm downloads" /></a>
15
+ <a href="https://github.com/bymaxone/nest-realtime/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/bymaxone/nest-realtime/ci.yml?branch=main&style=flat-square&colorA=000000&label=CI" alt="CI status" /></a>
16
+ <a href="https://github.com/bymaxone/nest-realtime/actions/workflows/ci.yml"><img src="https://img.shields.io/badge/coverage-100%25-brightgreen?style=flat-square&colorA=000000" alt="coverage" /></a>
17
+ <a href="https://github.com/bymaxone/nest-realtime/blob/main/docs/mutation_testing_results.md"><img src="https://img.shields.io/badge/mutation-99.27%25-brightgreen?style=flat-square&colorA=000000" alt="mutation score" /></a>
18
+ <a href="https://scorecard.dev/viewer/?uri=github.com/bymaxone/nest-realtime"><img src="https://api.scorecard.dev/projects/github.com/bymaxone/nest-realtime/badge?style=flat-square" alt="OpenSSF Scorecard" /></a>
19
+ <a href="https://github.com/bymaxone/nest-realtime/blob/main/LICENSE"><img src="https://img.shields.io/github/license/bymaxone/nest-realtime?style=flat-square&colorA=000000&colorB=000000" alt="license" /></a>
20
+ <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" /></a>
21
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" /></a>
22
+ </p>
23
+
24
+ <p align="center">
25
+ <a href="https://github.com/bymaxone/nest-realtime">GitHub</a> ·
26
+ <a href="https://github.com/bymaxone/nest-realtime/issues">Issues</a> ·
27
+ <a href="#-quick-start">Quick Start</a> ·
28
+ <a href="#-api-reference">API Reference</a> ·
29
+ <a href="https://github.com/bymaxone/nest-realtime-example">Example App</a>
30
+ </p>
31
+
32
+ ---
33
+
34
+ ## ✨ Overview
35
+
36
+ `@bymax-one/nest-realtime` is a **transport-agnostic realtime channel** shipped as a single npm package with **3 subpath exports** — covering the NestJS server module, the shared type contracts, and the React hooks that consume them.
37
+
38
+ The default transport is **Server-Sent Events**: browser-native, plain HTTP, no client library to ship. WebSocket via Socket.IO is one config flag away, and `'both'` runs them side by side. Your application code calls the same `RealtimeService` either way — the transport is a deployment decision, not an architectural one.
39
+
40
+ ### Why nest-realtime?
41
+
42
+ - **🎯 One API, any transport** — `emitToUser`, `emitToTenant`, `emitToRoom`, `broadcast`, and `disconnect` behave identically on SSE, WebSocket, or both. Migrating between transports changes a config line, not your call sites.
43
+ - **📡 SSE first, and that is the point** — SSE reconnects natively, replays through `Last-Event-ID`, and traverses proxies as ordinary HTTP. Most apps only push server → client, and for those WebSocket is a dependency you pay for without using.
44
+ - **🔌 Auth stays yours** — The library never verifies a JWT, never imports an auth package. You implement `IConnectionAuthenticator`; cookie, ticket, and bearer patterns are all supported. This is enforced structurally, not by convention.
45
+ - **🏢 Multi-tenant by construction** — Every connection auto-joins `user:{id}` and, when present, `tenant:{id}`. Tenant scoping is a room convention, not an afterthought bolted onto a chat library.
46
+ - **🪶 Nothing in your bundle you didn't ask for** — `"dependencies": {}` on the server, and `socket.io-client` is reached through `await import()` so an SSE-only frontend ships **2.26 KB brotli** instead of ~80 KB.
47
+
48
+ ```
49
+ pnpm add @bymax-one/nest-realtime
50
+ ```
51
+
52
+ ---
53
+
54
+ ## 🔥 Features
55
+
56
+ ### 📡 Transports
57
+
58
+ - ✅ **SSE (default)** — native browser reconnect, `Last-Event-ID` replay, `: keepalive` heartbeat tuned for real proxies
59
+ - ✅ **WebSocket (opt-in)** — Socket.IO gateway behind `transport: 'websocket'`, with full-duplex `emit`
60
+ - ✅ **Composite mode** — `transport: 'both'` fans a single emit out to clients on either transport
61
+ - ✅ **Unified contract** — every transport implements `ITransport`, so `RealtimeService` never branches
62
+
63
+ ### 🔐 Security & Auth
64
+
65
+ - ✅ **Auth inversion** — the consumer plugs `IConnectionAuthenticator`; the library owns no credentials
66
+ - ✅ **Zero auth imports** — `src/` contains no reference to `@nestjs/jwt`, `passport-*`, or any auth package, verified in CI
67
+ - ✅ **Three handshake patterns** — HttpOnly cookie (SSE-safe), one-time ticket, and bearer header (WebSocket only)
68
+ - ✅ **Periodic re-authentication** — revalidate credentials on an interval, with a positive-result cache
69
+ - ✅ **Tenant from the token, never the body** — `tenantId` comes from the authenticated result via `tenantResolver`
70
+
71
+ ### 🏢 Multi-Tenant & Delivery
72
+
73
+ - ✅ **Room conventions** — `user:{id}`, `tenant:{id}`, `resource:{type}:{id}`, with the first two auto-joined
74
+ - ✅ **Offline queue** — `IOfflineQueueStorage` holds events for absent users and flushes them on reconnect
75
+ - ✅ **Replay buffer** — per-user ring buffer answers `Last-Event-ID` after a dropped SSE stream
76
+ - ✅ **FIFO connection limits** — the oldest connection is evicted, so a new tab never gets a 429
77
+ - ✅ **Presence** — optional `IPresenceStorage` powers `presence:online` / `presence:offline`
78
+
79
+ ### 🧩 Developer Experience
80
+
81
+ - ✅ **3 subpath exports** — server, shared types, and React; tree-shakeable, ESM + CJS dual output
82
+ - ✅ **Dynamic module** — `forRoot()` and `forRootAsync()` with `useFactory` / `useClass` / `useExisting`
83
+ - ✅ **Strict TypeScript, zero `any`** — `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` on
84
+ - ✅ **Horizontal scaling** — `IRealtimePubSub` for SSE fan-out, `@socket.io/redis-adapter` for WebSocket
85
+ - ✅ **Bundle gate in CI** — the SSE-only React bundle is measured on every build and fails over budget
86
+
87
+ ---
88
+
89
+ ## 📦 Subpath Exports
90
+
91
+ One package, three entry points — import only what your app needs:
92
+
93
+ | Subpath | Import | Purpose | Dependencies |
94
+ | ---------- | --------------------------------- | ---------------------------------------------- | :-------------: |
95
+ | **Server** | `@bymax-one/nest-realtime` | NestJS module, transports, services, contracts | NestJS 11, rxjs |
96
+ | **Shared** | `@bymax-one/nest-realtime/shared` | Types, room prefixes, event names, error codes | None |
97
+ | **React** | `@bymax-one/nest-realtime/react` | Hooks & `RealtimeProvider` | React 19 |
98
+
99
+ ```
100
+ shared (zero deps)
101
+ ↗ ↖
102
+ server react
103
+ ```
104
+
105
+ The `shared` subpath carries no Node or NestJS import, so the same event names and error codes are used on both sides of the wire without duplicating a constant.
106
+
107
+ ---
108
+
109
+ > [!TIP]
110
+ > Prefer to learn from a working app? See the [nest-realtime-example](https://github.com/bymaxone/nest-realtime-example) — a NestJS + React project wired with this library.
111
+
112
+ ## 🚀 Quick Start
113
+
114
+ ### 1. Install
115
+
116
+ ```bash
117
+ # Using pnpm (recommended)
118
+ pnpm add @bymax-one/nest-realtime
119
+
120
+ # Using npm
121
+ npm install @bymax-one/nest-realtime
122
+
123
+ # Using yarn
124
+ yarn add @bymax-one/nest-realtime
125
+ ```
126
+
127
+ > [!IMPORTANT]
128
+ > You must also install the **peer dependencies** for the subpaths you use. The library declares `"dependencies": {}` — nothing is installed on your behalf.
129
+
130
+ ```bash
131
+ # Server subpath (required)
132
+ pnpm add @nestjs/common @nestjs/core rxjs reflect-metadata
133
+
134
+ # WebSocket transport (optional — only for transport: 'websocket' | 'both')
135
+ pnpm add @nestjs/websockets @nestjs/platform-socket.io socket.io
136
+
137
+ # Horizontal scaling (optional)
138
+ pnpm add ioredis @socket.io/redis-adapter
139
+
140
+ # React subpath (optional)
141
+ pnpm add react react-dom
142
+
143
+ # WebSocket on the frontend (optional)
144
+ pnpm add socket.io-client
145
+ ```
146
+
147
+ ### 2. Implement the Authenticator Interface
148
+
149
+ This is the only interface you are required to provide. The library calls it once per connection and never inspects the credential itself.
150
+
151
+ ```typescript
152
+ import type {
153
+ IConnectionAuthenticator,
154
+ ConnectionAuthContext,
155
+ AuthenticationResult,
156
+ } from '@bymax-one/nest-realtime'
157
+ import { verifyAccessToken } from './jwt'
158
+
159
+ export class CookieAuthenticator implements IConnectionAuthenticator {
160
+ async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
161
+ const token = ctx.cookies['access_token']
162
+ if (!token) return null
163
+
164
+ try {
165
+ const claims = await verifyAccessToken(token)
166
+ return { userId: claims.sub, tenantId: claims.tid }
167
+ } catch {
168
+ return null // null rejects the connection
169
+ }
170
+ }
171
+ }
172
+ ```
173
+
174
+ > [!NOTE]
175
+ > Returning `null` rejects the connection — throwing is not required. See [Auth Inversion](#-security-model) for the ticket and bearer patterns.
176
+
177
+ ### 3. Register the Module
178
+
179
+ ```typescript
180
+ // app.module.ts
181
+ import { Module } from '@nestjs/common'
182
+ import { BymaxRealtimeModule } from '@bymax-one/nest-realtime'
183
+ import { CookieAuthenticator } from './auth/cookie-authenticator'
184
+
185
+ @Module({
186
+ imports: [
187
+ BymaxRealtimeModule.forRoot({
188
+ transport: 'sse',
189
+ authenticator: new CookieAuthenticator(),
190
+ }),
191
+ ],
192
+ })
193
+ export class AppModule {}
194
+ ```
195
+
196
+ Clients now connect to `GET /realtime/sse` (configurable via `sse.endpoint`).
197
+
198
+ ### 4. Emit From Anywhere
199
+
200
+ Inject `RealtimeService` into any provider or controller:
201
+
202
+ ```typescript
203
+ import { Controller, Post, Body, Param } from '@nestjs/common'
204
+ import { RealtimeService } from '@bymax-one/nest-realtime'
205
+
206
+ @Controller('invoices')
207
+ export class InvoicesController {
208
+ constructor(private readonly realtime: RealtimeService) {}
209
+
210
+ @Post(':id/pay')
211
+ async pay(@Param('id') invoiceId: string, @Body() body: { userId: string; amount: number }) {
212
+ await this.realtime.emitToUser(body.userId, 'invoice.paid', {
213
+ invoiceId,
214
+ amount: body.amount,
215
+ })
216
+ }
217
+ }
218
+ ```
219
+
220
+ > [!IMPORTANT]
221
+ > The emit signature is `(target, eventName, data)` — three arguments. The event name is a separate string, not a field inside the payload.
222
+
223
+ ### 5. Consume in React
224
+
225
+ Wrap the subtree once, then read from it with hooks:
226
+
227
+ ```tsx
228
+ // App.tsx
229
+ import { RealtimeProvider } from '@bymax-one/nest-realtime/react'
230
+
231
+ export default function App() {
232
+ return (
233
+ <RealtimeProvider options={{ url: '/realtime/sse', eventNames: ['invoice.paid'] }}>
234
+ <InvoiceList />
235
+ </RealtimeProvider>
236
+ )
237
+ }
238
+ ```
239
+
240
+ ```tsx
241
+ // InvoiceList.tsx
242
+ import { useRealtimeContext } from '@bymax-one/nest-realtime/react'
243
+
244
+ export function InvoiceList() {
245
+ const { events, connected } = useRealtimeContext()
246
+
247
+ return (
248
+ <>
249
+ <span>{connected ? '🟢 live' : '🔴 disconnected'}</span>
250
+ <ul>
251
+ {events.map((e, i) => (
252
+ <li key={i}>
253
+ {String(e.type)} — {JSON.stringify(e.data)}
254
+ </li>
255
+ ))}
256
+ </ul>
257
+ </>
258
+ )
259
+ }
260
+ ```
261
+
262
+ > [!NOTE]
263
+ > Events carry an `id` on the SSE branch only — the WebSocket branch has no per-event id, so the shared context type does not expose one. Narrow on `transport === 'sse'` if you need it.
264
+
265
+ > [!IMPORTANT]
266
+ > `EventSource` delivers a **named** event only to a listener registered for that exact name. Application-level names such as `invoice.paid` must be listed in `eventNames`, or they never reach the hook. Reserved and presence events are subscribed automatically.
267
+
268
+ ### 6. Scale Across Instances
269
+
270
+ SSE connections live on the instance that accepted them. To fan an emit out to every instance, provide a pub/sub backend:
271
+
272
+ ```typescript
273
+ import {
274
+ BymaxRealtimeModule,
275
+ RedisRealtimePubSub,
276
+ RedisOfflineQueue,
277
+ } from '@bymax-one/nest-realtime'
278
+ import Redis from 'ioredis'
279
+
280
+ const redis = new Redis(process.env.REDIS_URL ?? 'redis://localhost:6379')
281
+
282
+ BymaxRealtimeModule.forRoot({
283
+ transport: 'sse',
284
+ authenticator: new CookieAuthenticator(),
285
+ pubsub: new RedisRealtimePubSub({ client: redis }),
286
+ offlineQueue: new RedisOfflineQueue({ client: redis }),
287
+ sse: { heartbeatMs: 25_000, replayBufferSize: 100, maxConnectionsPerUser: 5 },
288
+ })
289
+ ```
290
+
291
+ For WebSocket, pass an ioredis client to `websocket.redisAdapter.pubClient` and `@socket.io/redis-adapter` is registered for you.
292
+
293
+ ---
294
+
295
+ ## ⚙️ Configuration
296
+
297
+ All options are passed to `forRoot()` / `forRootAsync()`. Only `transport` and `authenticator` are required.
298
+
299
+ | Group | Key Options | Default |
300
+ | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
301
+ | **transport** | `'sse'` \| `'websocket'` \| `'both'` | — (**required**) |
302
+ | **authenticator** | `IConnectionAuthenticator` | — (**required**) |
303
+ | **service** | `name`, `version` — identifies the emitting service in event metadata | — |
304
+ | **tenantResolver** | `(auth) => string \| undefined` — derives `tenantId` from the auth result | `auth.tenantId` |
305
+ | **hooks** | `onConnect`, `onDisconnect`, `onError`, `onReauthenticationFailed` (fire-and-forget) | — |
306
+ | **pubsub** | `IRealtimePubSub` — cross-instance fan-out for SSE | `InMemoryPubSub` |
307
+ | **offlineQueue** | `IOfflineQueueStorage` — events held while a user is away | — (disabled) |
308
+ | **presence** | `IPresenceStorage` — online-user tracking | — (disabled) |
309
+ | **sse** | `endpoint`, `heartbeatMs`, `replayBufferSize`, `maxConnectionsPerUser`, `emitConnectionEvent` | `/realtime/sse`, `30000`, `100`, `5`, `true` |
310
+ | **websocket** | `namespace`, `cors`, `maxHttpBufferSize`, `pingIntervalMs`, `pingTimeoutMs`, `maxConnectionsPerUser`, `emitConnectionEvent`, `redisAdapter` | `'/'`, — (Socket.IO defaults) |
311
+ | **reauthenticationPolicy** | `intervalSeconds`, `onFailure` (`'disconnect'` \| `'event'`), `cacheTtlMs` | `300`, `'disconnect'`, `60000` |
312
+
313
+ > [!NOTE]
314
+ > `websocket.maxConnectionsPerUser` is **opt-in** and unlimited unless set to a positive number, while `sse.maxConnectionsPerUser` defaults to `5`. The two transports differ here on purpose: an SSE stream holds an HTTP connection open, a Socket.IO client multiplexes.
315
+
316
+ The full reference, including `forRootAsync` with `useFactory` / `useClass` / `useExisting`, is in [docs/technical_specification.md](./docs/technical_specification.md) §4.
317
+
318
+ ---
319
+
320
+ ## 🏗️ Architecture
321
+
322
+ The package runs **inside** your NestJS application as a dynamic module — not as a separate realtime server:
323
+
324
+ ```
325
+ ┌────────────────────────────────────────────────────┐
326
+ │ Your NestJS Application │
327
+ │ │
328
+ │ ┌──────────────────────────────────────────────┐ │
329
+ │ │ @bymax-one/nest-realtime │ │
330
+ │ │ │ │
331
+ │ │ RealtimeService ──→ ITransport │ │
332
+ │ │ │ ├── SseTransport │ │
333
+ │ │ │ ├── WebSocket… │ │
334
+ │ │ │ └── Composite… │ │
335
+ │ │ ↓ │ │
336
+ │ │ ConnectionRegistry ←→ RoomRegistry │ │
337
+ │ └────────┬──────────────┬──────────────┬───────┘ │
338
+ │ │ │ │ │
339
+ │ ┌───────▼──────┐ ┌─────▼──────┐ ┌─────▼───────┐ │
340
+ │ │ IConnection │ │ IRealtime │ │ IOffline │ │
341
+ │ │ Authenticator│ │ PubSub │ │ QueueStorage│ │
342
+ │ │ (yours) │ │ (optional) │ │ (optional) │ │
343
+ │ └──────────────┘ └────────────┘ └─────────────┘ │
344
+ └────────────────────────────────────────────────────┘
345
+ │ │
346
+ SSE (HTTP stream) WebSocket (Socket.IO)
347
+ └────────→ Browser ←─────┘
348
+ ```
349
+
350
+ ### Design Principles
351
+
352
+ | Principle | Description |
353
+ | ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
354
+ | **🔌 Interface-Driven** | Authentication, pub/sub, offline queue, and presence are contracts you implement — Redis reference implementations ship, none are forced |
355
+ | **🔀 Transport-Agnostic** | `RealtimeService` talks to `ITransport`; adding or swapping a transport never touches application code |
356
+ | **🛡️ Auth Inversion** | The library holds no credential logic, so an auth vulnerability cannot originate here |
357
+ | **🪶 Zero Runtime Deps** | `"dependencies": {}` — every dependency is a peer, and optional ones are marked in `peerDependenciesMeta` |
358
+ | **🌳 Tree-Shakeable** | `sideEffects: false`, subpath exports, and a dynamic `import()` that keeps `socket.io-client` out of the SSE bundle |
359
+
360
+ ### Cross-Instance Emit Flow
361
+
362
+ An emit delivers locally **and** publishes once. Every other instance's subscriber re-emits through local-only paths (`emitToUserLocal`, …), so a message is never republished and cannot loop. Connection revocation crosses instances as an `op: 'disconnect'` message on the same channel.
363
+
364
+ Sizing guidance and adapter trade-offs are in [docs/architecture/scaling-cheatsheet.md](./docs/architecture/scaling-cheatsheet.md).
365
+
366
+ ---
367
+
368
+ ## 🔐 Security Model
369
+
370
+ ### Auth Inversion
371
+
372
+ This library **never** verifies a JWT, hashes a password, or imports an authentication package. It calls `IConnectionAuthenticator.authenticate()` once per connection and trusts the `AuthenticationResult` you return.
373
+
374
+ This is a **structural guarantee**, not a guideline — `src/` is audited in CI for any reference to `@bymax-one/nest-auth`, `@nestjs/jwt`, or `passport-*`:
375
+
376
+ ```bash
377
+ grep -rE "@nestjs/jwt|@bymax-one/nest-auth|passport" src/ # must return zero
378
+ ```
379
+
380
+ The consequence is worth stating plainly: a credential-handling vulnerability cannot originate in this package, because the code that would contain it does not exist here. It also means **you** are responsible for the bridge — vulnerabilities in a bridge implementation belong to that project, as [SECURITY.md](./SECURITY.md) records.
381
+
382
+ ### Handshake Patterns
383
+
384
+ | Pattern | Transport | Credential source | Notes |
385
+ | ------------------- | --------- | ------------------------------ | ----------------------------------------------------------------- |
386
+ | **HttpOnly cookie** | SSE + WS | `ctx.cookies` | Recommended. The only pattern where the browser sends it for you. |
387
+ | **One-time ticket** | SSE + WS | `ctx.query['ticket']` | Short-lived, single-use. The gateway normalizes it to one string. |
388
+ | **Bearer header** | WS only | `ctx.headers['authorization']` | `EventSource` cannot send custom headers — SSE must not use this. |
389
+
390
+ ```typescript
391
+ export class TicketAuthenticator implements IConnectionAuthenticator {
392
+ constructor(private readonly tickets: TicketStore) {}
393
+
394
+ async authenticate(ctx: ConnectionAuthContext): Promise<AuthenticationResult | null> {
395
+ const ticket = ctx.query['ticket']
396
+ if (!ticket || Array.isArray(ticket)) return null
397
+ return this.tickets.consume(ticket) // null when expired or already used
398
+ }
399
+ }
400
+ ```
401
+
402
+ A complete `@bymax-one/nest-auth` bridge is in [docs/examples/nest-auth-bridge.md](./docs/examples/nest-auth-bridge.md); the per-transport handshake differences are in [docs/architecture/auth-handshake-differences.md](./docs/architecture/auth-handshake-differences.md).
403
+
404
+ ### Re-Authentication
405
+
406
+ Long-lived connections outlive short-lived tokens. `reauthenticationPolicy` revalidates on an interval and either drops the connection or emits `connection:reauthentication-failed`, depending on `onFailure`. Successful checks are cached for `cacheTtlMs` so a busy connection is not revalidated on every event.
407
+
408
+ ### Security Checklist
409
+
410
+ When integrating `@bymax-one/nest-realtime` in production, verify each of the following:
411
+
412
+ - The SSE endpoint is served over HTTPS — `Last-Event-ID` replays past events to whoever reconnects
413
+ - `tenantId` is derived from the authenticated result, never from a query parameter or request body
414
+ - Tickets are single-use and short-lived; `consume()` must be atomic under concurrency
415
+ - `websocket.cors.origin` is an explicit allowlist, not `true`, in any browser-facing deployment
416
+ - `maxConnectionsPerUser` is set for WebSocket if clients are untrusted — it is unlimited by default
417
+ - Reserved event names are not reused for application events (see the [catalog](#reserved-events))
418
+
419
+ ---
420
+
421
+ ## 🛡️ Security Table
422
+
423
+ | Layer | Implementation |
424
+ | --------------------- | ------------------------------------------------------------------------------ |
425
+ | Credential validation | Delegated entirely to consumer-supplied `IConnectionAuthenticator` |
426
+ | Auth library imports | None — enforced by a CI grep over `src/` |
427
+ | Tenant isolation | Room-scoped (`tenant:{id}`), resolved from the authenticated result |
428
+ | Connection revocation | `disconnect(connectionId)`, propagated cross-instance via `op: 'disconnect'` |
429
+ | Credential expiry | Interval re-authentication with `disconnect` or event on failure |
430
+ | Connection flooding | FIFO eviction per user — oldest closed, new admitted, never a 429 |
431
+ | SSE transport headers | `X-Accel-Buffering: no` and `Cache-Control: no-cache, no-transform` by default |
432
+ | WebSocket origin | Explicit `cors` config passed straight to Socket.IO |
433
+
434
+ > [!IMPORTANT]
435
+ > This package holds **zero credential logic**. That is its central security property — and it means the strength of your realtime auth is exactly the strength of the authenticator you plug in.
436
+
437
+ ---
438
+
439
+ ## 🧱 Tech Stack
440
+
441
+ <p>
442
+ <img src="https://img.shields.io/badge/NestJS-11-E0234E?style=flat-square&logo=nestjs&logoColor=white" alt="NestJS" />
443
+ <img src="https://img.shields.io/badge/TypeScript-strict-3178C6?style=flat-square&logo=typescript&logoColor=white" alt="TypeScript" />
444
+ <img src="https://img.shields.io/badge/React-19-61DAFB?style=flat-square&logo=react&logoColor=black" alt="React" />
445
+ <img src="https://img.shields.io/badge/RxJS-7-B7178C?style=flat-square&logo=reactivex&logoColor=white" alt="RxJS" />
446
+ <img src="https://img.shields.io/badge/Socket.IO-4-010101?style=flat-square&logo=socket.io&logoColor=white" alt="Socket.IO" />
447
+ <img src="https://img.shields.io/badge/Node.js-24%2B-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node.js" />
448
+ <img src="https://img.shields.io/badge/Redis-optional-DC382D?style=flat-square&logo=redis&logoColor=white" alt="Redis" />
449
+ <img src="https://img.shields.io/badge/Jest-30-C21325?style=flat-square&logo=jest&logoColor=white" alt="Jest" />
450
+ </p>
451
+
452
+ ---
453
+
454
+ ## 🧪 Testing & Quality
455
+
456
+ A realtime channel fails in ways that are hard to reproduce — dropped streams, races between reconnect and revocation, one instance not seeing another's emit. The suite is built so those failures are caught by a test, not by a user.
457
+
458
+ - ✅ **100% coverage** — statements, branches, functions, and lines, enforced as a release gate
459
+ - ✅ **99.27% mutation score** — 678 / 683 mutants killed, verified with [Stryker](https://stryker-mutator.io/) (break threshold 95)
460
+ - ✅ **607 tests** — 574 unit and integration across 36 suites, plus 33 end-to-end across 6
461
+ - ✅ **Cross-instance e2e** — real Redis pub/sub fan-out between two live instances, not a mocked channel
462
+ - ✅ **Bundle-size gate** — the SSE-only React bundle is measured on every build and fails over budget
463
+
464
+ ```bash
465
+ pnpm test # unit + integration
466
+ pnpm test:e2e # end-to-end (single instance, no Redis needed)
467
+ pnpm test:cov:all # 100% coverage gate
468
+ pnpm mutation # Stryker mutation testing (~15-25 min)
469
+ pnpm build && pnpm size
470
+ ```
471
+
472
+ Cross-instance e2e needs a Redis instance:
473
+
474
+ ```bash
475
+ REDIS_URL=redis://localhost:6379 pnpm test:e2e
476
+ ```
477
+
478
+ > [!NOTE]
479
+ > Line coverage proves a line _executed_ under test; mutation testing proves a test _would fail_ if that line were wrong. The full methodology and per-area breakdown are in [docs/mutation_testing_results.md](./docs/mutation_testing_results.md).
480
+
481
+ ---
482
+
483
+ ## 📖 API Reference
484
+
485
+ ### RealtimeService
486
+
487
+ The unified emit API. Identical on every transport.
488
+
489
+ | Method | Description |
490
+ | ------------------------------------- | ----------------------------------------- |
491
+ | `emitToUser(userId, event, data)` | Deliver to every connection of one user |
492
+ | `emitToTenant(tenantId, event, data)` | Deliver to every connection in a tenant |
493
+ | `emitToRoom(roomId, event, data)` | Deliver to an arbitrary room |
494
+ | `broadcast(event, data)` | Deliver to every connected client |
495
+ | `joinRoom(connectionId, roomId)` | Add a connection to a room |
496
+ | `leaveRoom(connectionId, roomId)` | Remove a connection from a room |
497
+ | `disconnect(connectionId, reason?)` | Revoke a connection, cross-instance aware |
498
+
499
+ All methods return `Promise<void>`.
500
+
501
+ ### ConnectionRegistry
502
+
503
+ Read-side view of live connections — useful for admin endpoints and metrics.
504
+
505
+ | Method | Returns |
506
+ | -------------------------------- | ------------------------------------------------ |
507
+ | `byUser(userId, transport?)` | `ConnectionRecord[]` for one user |
508
+ | `byTenant(tenantId, transport?)` | `ConnectionRecord[]` for one tenant |
509
+ | `allByTransport(transport)` | `ConnectionRecord[]` on `'sse'` or `'websocket'` |
510
+ | `get(connectionId)` | `ConnectionRecord \| undefined` |
511
+ | `count()` / `countUsers()` | Live connection count / distinct user count |
512
+
513
+ ### Contracts
514
+
515
+ | Interface | Required | Purpose |
516
+ | --------------------------- | :------: | ----------------------------------------------------------- |
517
+ | `IConnectionAuthenticator` | ✅ | Validate a connection, return `userId` / `tenantId` |
518
+ | `IRealtimePubSub` | — | Cross-instance fan-out for SSE |
519
+ | `IOfflineQueueStorage` | — | Hold events for disconnected users |
520
+ | `IPresenceStorage` | — | Track who is online |
521
+ | `IConnectionLifecycleHooks` | — | Fire-and-forget connect / disconnect / error callbacks |
522
+ | `ITransport` | — | Implemented by the library; the seam every transport shares |
523
+
524
+ Reference implementations shipped: `InMemoryPubSub` (default), `RedisRealtimePubSub`, `RedisOfflineQueue`.
525
+
526
+ ### Rooms
527
+
528
+ | Room ID | Used for | Auto-joined |
529
+ | ---------------------- | ----------------------------------------------- | ----------------------------- |
530
+ | `user:{userId}` | Every connection belonging to one user | ✅ Always |
531
+ | `tenant:{tenantId}` | Every connection in a tenant | ✅ When `tenantId` is present |
532
+ | `resource:{type}:{id}` | Per-resource events, e.g. `resource:invoice:42` | Manual — call `joinRoom` |
533
+
534
+ ```typescript
535
+ import { composeRoomId } from '@bymax-one/nest-realtime'
536
+
537
+ composeRoomId('USER', userId) // → "user:u_abc"
538
+ composeRoomId('TENANT', tenantId) // → "tenant:t_acme"
539
+ composeRoomId('RESOURCE', 'invoice', invoiceId) // → "resource:invoice:42"
540
+ ```
541
+
542
+ ### Reserved Events
543
+
544
+ Emitted by the library. Do not reuse these names for application events.
545
+
546
+ | Event | Meaning |
547
+ | -------------------------------------- | ------------------------------------------------------- |
548
+ | `connection:established` | Handshake accepted (suppress via `emitConnectionEvent`) |
549
+ | `connection:reauthentication-failed` | Credentials no longer valid |
550
+ | `connection:credential-expiring` | Credential nearing expiry |
551
+ | `room:joined` / `room:left` | Room membership changed |
552
+ | `error` | Transport-level error |
553
+ | `presence:online` / `presence:offline` | Presence changed (requires `IPresenceStorage`) |
554
+
555
+ > [!NOTE]
556
+ > The SSE heartbeat is a `: keepalive` **comment line**, not a named event. It never appears in the `Last-Event-ID` id-space and never reaches a client listener.
557
+
558
+ ### Error Codes
559
+
560
+ `REALTIME_INVALID_OPTIONS` · `REALTIME_NO_AUTHENTICATOR` · `REALTIME_AUTH_FAILED` · `REALTIME_REAUTHENTICATION_FAILED` · `REALTIME_TOO_MANY_CONNECTIONS` · `REALTIME_INVALID_TICKET` · `REALTIME_PUBSUB_UNAVAILABLE` · `REALTIME_PAYLOAD_TOO_LARGE` · `REALTIME_REPLAY_BUFFER_MISS`
561
+
562
+ ### DI Tokens
563
+
564
+ `REALTIME_OPTIONS_TOKEN` · `REALTIME_TRANSPORT_TOKEN` · `REALTIME_AUTHENTICATOR_TOKEN` · `REALTIME_PUBSUB_TOKEN` · `REALTIME_OFFLINE_QUEUE_TOKEN` · `REALTIME_PRESENCE_TOKEN` · `REALTIME_HOOKS_TOKEN` · `REALTIME_INSTANCE_ID_TOKEN`
565
+
566
+ ### React Hooks
567
+
568
+ | Hook | Returns |
569
+ | -------------------------------- | --------------------------------------------------------------------------------------------------------------- |
570
+ | `useRealtime(options)` | `{ transport, connected, events, lastEvent, error, reconnectAttempts, reconnect, emit }` — opens the connection |
571
+ | `useRealtimeContext()` | The same value, from the nearest `<RealtimeProvider>` — throws when used outside one |
572
+ | `useRealtimeConnection(options)` | `{ connected, error, reconnectAttempts, reconnect }` — status only, no events array |
573
+ | `usePresence()` | `{ onlineUserIds, isOnline(userId), count }` — reads presence events from the provider |
574
+
575
+ `RealtimeProvider` takes a single `options` prop of type `UseRealtimeOptions`:
576
+
577
+ | Option | Type | Default | Notes |
578
+ | -------------------- | -------------------------------- | ------------- | --------------------------------------------------- |
579
+ | `url` | `string` | — (required) | `ws://` or `wss://` selects WebSocket automatically |
580
+ | `transport` | `'auto' \| 'sse' \| 'websocket'` | `'auto'` | Overrides URL-scheme detection |
581
+ | `eventNames` | `readonly string[]` | — | **SSE only** — application event names to subscribe |
582
+ | `withCredentials` | `boolean` | `false` | **SSE only** — send cookies cross-origin |
583
+ | `auth` | `{ ticket?, token? }` | — | **WebSocket only** — handshake credentials |
584
+ | `path` | `string` | `/socket.io` | **WebSocket only** — Socket.IO path |
585
+ | `reconnectInitialMs` | `number` | `1000` | **SSE only** — initial backoff |
586
+ | `reconnectMaxMs` | `number` | `30000` | **SSE only** — backoff ceiling |
587
+ | `maxAttempts` | `number` | — (unlimited) | **SSE only** — give up and close after N failures |
588
+
589
+ > [!NOTE]
590
+ > `emit` is WebSocket-exclusive — SSE is server → client only. `reconnectAttempts` is always `0` on WebSocket, where Socket.IO owns the retry policy and exposes no count.
591
+
592
+ ---
593
+
594
+ ## 🚧 Deployment Notes
595
+
596
+ SSE connections are long-lived HTTP responses, and several common proxy defaults break them silently:
597
+
598
+ | Concern | Fix |
599
+ | ------------------------ | ------------------------------------------------------------------------------------------------------ |
600
+ | **Response compression** | Disable on the SSE endpoint — `Content-Encoding: gzip` buffers the body and defeats streaming |
601
+ | **Proxy buffering** | Nginx `proxy_buffering off`. The library already sends `X-Accel-Buffering: no` |
602
+ | **CDN caching** | `Cache-Control: no-cache, no-transform` — set by the library on the SSE response |
603
+ | **Idle timeout** | Must exceed `sse.heartbeatMs` (default 30 s). AWS ALB's 60 s default is compatible |
604
+ | **WebSocket + polling** | Enable sticky sessions. The Redis adapter syncs messages between instances, but not handshake affinity |
605
+
606
+ Platform-specific configuration is in [docs/proxies-cheat-sheet.md](./docs/proxies-cheat-sheet.md).
607
+
608
+ ---
609
+
610
+ ## 🗺️ Roadmap
611
+
612
+ The items below are directional — none are shipping today. The list exists so contributors can see where the library is headed and where help is most useful. Open an issue to discuss priorities or propose a design.
613
+
614
+ | Area | Item | Status |
615
+ | ----------------------- | -------------------------------------------------------------------------------------------- | --------- |
616
+ | Presence | Redis reference implementation of `IPresenceStorage` — today the interface ships without one | Planned |
617
+ | Pub/sub adapters | Reference implementations beyond Redis (NATS, Redis Streams) for `IRealtimePubSub` | Exploring |
618
+ | Observability | Built-in metrics for connection counts, emit latency, and replay-buffer misses | Planned |
619
+ | Backpressure | Per-connection send queues with a configurable policy for slow consumers | Exploring |
620
+ | Client acknowledgements | Optional delivery receipts on the WebSocket transport | Exploring |
621
+ | Framework adapters | Vue and Svelte subpaths built on the same shared contracts | Exploring |
622
+
623
+ > Track progress and discuss proposals on the [issues board](https://github.com/bymaxone/nest-realtime/issues).
624
+
625
+ ---
626
+
627
+ ## 🤝 Contributing
628
+
629
+ Contributions are welcome! Please open an issue to discuss substantial changes before submitting a pull request.
630
+
631
+ ```bash
632
+ # Clone the repository
633
+ git clone https://github.com/bymaxone/nest-realtime.git
634
+ cd nest-realtime
635
+
636
+ # Install dependencies
637
+ pnpm install
638
+
639
+ # Run tests
640
+ pnpm test
641
+
642
+ # Build
643
+ pnpm build
644
+
645
+ # Type check
646
+ pnpm typecheck
647
+ ```
648
+
649
+ Every change must keep the full gate green:
650
+
651
+ ```bash
652
+ pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm size
653
+ ```
654
+
655
+ ---
656
+
657
+ ## 🔒 Security Policy
658
+
659
+ If you discover a security vulnerability, please **do not** open a public issue. Instead, email us at **security@bymax.one** with details. We take security seriously and will respond promptly. Full policy and scope: [SECURITY.md](./SECURITY.md).
660
+
661
+ ---
662
+
663
+ ## 📄 License
664
+
665
+ [MIT](./LICENSE) © [Bymax One](https://github.com/bymaxone)
666
+
667
+ ---
668
+
669
+ <p align="center">
670
+ <sub>Built with ❤️ by <a href="https://github.com/bymaxone">Bymax One</a></sub>
671
+ </p>