@bymax-one/nest-realtime 1.2.0 → 1.2.2
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/CHANGELOG.md +170 -1
- package/README.md +155 -22
- package/dist/internal/index.cjs +153 -13
- package/dist/internal/index.d.cts +144 -14
- package/dist/internal/index.d.ts +144 -14
- package/dist/internal/index.mjs +153 -15
- package/dist/websocket/index.cjs +158 -93
- package/dist/websocket/index.d.cts +20 -1
- package/dist/websocket/index.d.ts +20 -1
- package/dist/websocket/index.mjs +159 -94
- package/package.json +1 -1
package/dist/internal/index.cjs
CHANGED
|
@@ -177,6 +177,31 @@ var RESERVED_EVENT_NAMES = {
|
|
|
177
177
|
ERROR: "error"
|
|
178
178
|
};
|
|
179
179
|
|
|
180
|
+
// src/server/utils/assert-identity.ts
|
|
181
|
+
function isBlank(value) {
|
|
182
|
+
return typeof value !== "string" || value.trim().length === 0;
|
|
183
|
+
}
|
|
184
|
+
function resolveAuthTenant(options, auth) {
|
|
185
|
+
const resolved = options.tenantResolver?.(auth) ?? auth.tenantId;
|
|
186
|
+
if (resolved === void 0 || resolved === null) {
|
|
187
|
+
const { tenantId: _dropped, ...withoutTenant } = auth;
|
|
188
|
+
return withoutTenant;
|
|
189
|
+
}
|
|
190
|
+
return { ...auth, tenantId: resolved };
|
|
191
|
+
}
|
|
192
|
+
function assertIdentityIsNotBlank(auth) {
|
|
193
|
+
if (isBlank(auth.userId)) {
|
|
194
|
+
throw new Error(
|
|
195
|
+
`${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a userId that is not a non-empty string. A blank identity indexes every such connection under one key and joins them to the same room; return a real userId, or reject the connection by returning null.`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
if (auth.tenantId !== void 0 && isBlank(auth.tenantId)) {
|
|
199
|
+
throw new Error(
|
|
200
|
+
`${REALTIME_ERROR_CODES.AUTH_FAILED}: the authenticator returned a tenantId that is present but not a non-empty string. Omit it, or return undefined or null, for a connection that belongs to no tenant \u2014 that is indexed under none and joins no tenant room, which an empty string is not.`
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
180
205
|
// src/server/utils/parse-cookie-header.ts
|
|
181
206
|
function parseCookieHeader(cookieHeader) {
|
|
182
207
|
const out = /* @__PURE__ */ Object.create(null);
|
|
@@ -194,7 +219,11 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
194
219
|
byId = /* @__PURE__ */ new Map();
|
|
195
220
|
byUserId = /* @__PURE__ */ new Map();
|
|
196
221
|
byTenantId = /* @__PURE__ */ new Map();
|
|
197
|
-
/**
|
|
222
|
+
/**
|
|
223
|
+
* Register a connection and index it by user and tenant.
|
|
224
|
+
*
|
|
225
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
226
|
+
*/
|
|
198
227
|
register(record) {
|
|
199
228
|
this.byId.set(record.connectionId, record);
|
|
200
229
|
this.addToSetMap(this.byUserId, record.userId, record.connectionId);
|
|
@@ -202,7 +231,11 @@ exports.ConnectionRegistry = class ConnectionRegistry {
|
|
|
202
231
|
this.addToSetMap(this.byTenantId, record.tenantId, record.connectionId);
|
|
203
232
|
}
|
|
204
233
|
}
|
|
205
|
-
/**
|
|
234
|
+
/**
|
|
235
|
+
* Remove a connection from every index. Returns the removed record, if any.
|
|
236
|
+
*
|
|
237
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
238
|
+
*/
|
|
206
239
|
unregister(connectionId) {
|
|
207
240
|
const record = this.byId.get(connectionId);
|
|
208
241
|
if (!record) return void 0;
|
|
@@ -786,6 +819,40 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
786
819
|
hooks;
|
|
787
820
|
offlineDelivery;
|
|
788
821
|
logger = new common.Logger(exports.SseSubscriptionHandler.name);
|
|
822
|
+
authenticated = /* @__PURE__ */ new WeakMap();
|
|
823
|
+
/**
|
|
824
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
825
|
+
*
|
|
826
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
827
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
828
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
829
|
+
* use would validate nothing.
|
|
830
|
+
*
|
|
831
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
832
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
833
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
834
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
835
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
836
|
+
*
|
|
837
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
838
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
839
|
+
* without a message.
|
|
840
|
+
*
|
|
841
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
842
|
+
* @returns The same result with the routing tenant resolved.
|
|
843
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
844
|
+
* but blank.
|
|
845
|
+
*/
|
|
846
|
+
resolveAndValidateIdentity(auth) {
|
|
847
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
848
|
+
try {
|
|
849
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
850
|
+
} catch (err) {
|
|
851
|
+
this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
|
|
852
|
+
throw new common.InternalServerErrorException();
|
|
853
|
+
}
|
|
854
|
+
return resolvedAuth;
|
|
855
|
+
}
|
|
789
856
|
/**
|
|
790
857
|
* Handle an incoming SSE connection request end-to-end.
|
|
791
858
|
*
|
|
@@ -797,16 +864,35 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
797
864
|
* @param req - The incoming request (SSE GET).
|
|
798
865
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
799
866
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
800
|
-
* @throws UnauthorizedException when authentication returns null
|
|
867
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
868
|
+
* credentials were rejected, which is a 401.
|
|
869
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
870
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
871
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
872
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
873
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
874
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
875
|
+
* written to the server log.
|
|
801
876
|
*/
|
|
802
877
|
async handle(req, res) {
|
|
803
878
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
804
879
|
res.setHeader("X-Accel-Buffering", "no");
|
|
805
|
-
const
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
880
|
+
const done = this.authenticated.get(req);
|
|
881
|
+
this.authenticated.delete(req);
|
|
882
|
+
let authenticated;
|
|
883
|
+
try {
|
|
884
|
+
authenticated = done ?? await this.authenticateRequest(req);
|
|
885
|
+
} catch (err) {
|
|
886
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
887
|
+
}
|
|
888
|
+
try {
|
|
889
|
+
return await this.openStream(req, res, authenticated);
|
|
890
|
+
} catch (err) {
|
|
891
|
+
throw this.serverError(err, "SSE handshake failed");
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
async openStream(req, res, authenticated) {
|
|
895
|
+
const { context, auth: resolvedAuth } = authenticated;
|
|
810
896
|
const connectionId = crypto.randomUUID();
|
|
811
897
|
const subject = new rxjs.Subject();
|
|
812
898
|
const close$ = new rxjs.Subject();
|
|
@@ -829,6 +915,33 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
829
915
|
queueEvents
|
|
830
916
|
});
|
|
831
917
|
}
|
|
918
|
+
/**
|
|
919
|
+
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
920
|
+
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
921
|
+
*/
|
|
922
|
+
async authenticateBeforeCommit(req) {
|
|
923
|
+
try {
|
|
924
|
+
this.authenticated.set(req, await this.authenticateRequest(req));
|
|
925
|
+
} catch (err) {
|
|
926
|
+
throw this.toClientError(err, "SSE authentication failed");
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
// Nest 11.2.3 streams `err.message`: only an authenticator's HTTP exception may pass as it is.
|
|
930
|
+
toClientError(err, what) {
|
|
931
|
+
return err instanceof common.HttpException ? err : this.serverError(err, what);
|
|
932
|
+
}
|
|
933
|
+
serverError(err, what) {
|
|
934
|
+
this.logger.error(
|
|
935
|
+
`${what} \u2014 responding 500: ${err instanceof Error ? err.message : String(err)}`
|
|
936
|
+
);
|
|
937
|
+
return new common.InternalServerErrorException();
|
|
938
|
+
}
|
|
939
|
+
async authenticateRequest(req) {
|
|
940
|
+
const context = buildAuthContext(req);
|
|
941
|
+
const auth = await this.transport.authenticate(context);
|
|
942
|
+
if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
943
|
+
return { context, auth: this.resolveAndValidateIdentity(auth) };
|
|
944
|
+
}
|
|
832
945
|
/**
|
|
833
946
|
* Build the live Observable using a subscribe-before-register pattern.
|
|
834
947
|
*
|
|
@@ -883,7 +996,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
883
996
|
this.fireHook(
|
|
884
997
|
() => this.hooks?.onError?.({ connectionId, error: err, transport: "sse" })
|
|
885
998
|
);
|
|
886
|
-
subscriber.error(err);
|
|
999
|
+
subscriber.error(this.serverError(err, "SSE registration failed"));
|
|
887
1000
|
});
|
|
888
1001
|
}
|
|
889
1002
|
/**
|
|
@@ -940,6 +1053,20 @@ function normalizeEndpointPath(endpoint) {
|
|
|
940
1053
|
// src/server/factories/sse-controller.factory.ts
|
|
941
1054
|
function createSseController(endpoint) {
|
|
942
1055
|
const ssePath = normalizeEndpointPath(endpoint);
|
|
1056
|
+
let SseAuthGuard = class {
|
|
1057
|
+
constructor(handler) {
|
|
1058
|
+
this.handler = handler;
|
|
1059
|
+
}
|
|
1060
|
+
handler;
|
|
1061
|
+
async canActivate(context) {
|
|
1062
|
+
await this.handler.authenticateBeforeCommit(context.switchToHttp().getRequest());
|
|
1063
|
+
return true;
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
SseAuthGuard = __decorateClass([
|
|
1067
|
+
common.Injectable(),
|
|
1068
|
+
__decorateParam(0, common.Inject(exports.SseSubscriptionHandler))
|
|
1069
|
+
], SseAuthGuard);
|
|
943
1070
|
let DynamicSseController = class {
|
|
944
1071
|
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
945
1072
|
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
@@ -953,6 +1080,7 @@ function createSseController(endpoint) {
|
|
|
953
1080
|
}
|
|
954
1081
|
};
|
|
955
1082
|
__decorateClass([
|
|
1083
|
+
common.UseGuards(SseAuthGuard),
|
|
956
1084
|
common.Sse(ssePath),
|
|
957
1085
|
__decorateParam(0, common.Req()),
|
|
958
1086
|
__decorateParam(1, common.Res({ passthrough: true }))
|
|
@@ -1029,7 +1157,13 @@ exports.RealtimeService = class RealtimeService {
|
|
|
1029
1157
|
broadcast(event, data) {
|
|
1030
1158
|
return this.transport.broadcast(event, data);
|
|
1031
1159
|
}
|
|
1032
|
-
/**
|
|
1160
|
+
/**
|
|
1161
|
+
* Add a specific connection to a room.
|
|
1162
|
+
*
|
|
1163
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
1164
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
1165
|
+
* receives that tenant's events.
|
|
1166
|
+
*/
|
|
1033
1167
|
joinRoom(connectionId, roomId) {
|
|
1034
1168
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1035
1169
|
}
|
|
@@ -1099,7 +1233,7 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1099
1233
|
this.positiveCache.clear();
|
|
1100
1234
|
}
|
|
1101
1235
|
/**
|
|
1102
|
-
* Run one revalidation cycle over
|
|
1236
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
1103
1237
|
*
|
|
1104
1238
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1105
1239
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1109,7 +1243,11 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1109
1243
|
*/
|
|
1110
1244
|
async runCycle() {
|
|
1111
1245
|
const now = Date.now();
|
|
1112
|
-
|
|
1246
|
+
const connections = [
|
|
1247
|
+
...this.connections.allByTransport("sse"),
|
|
1248
|
+
...this.connections.allByTransport("websocket")
|
|
1249
|
+
];
|
|
1250
|
+
for (const conn of connections) {
|
|
1113
1251
|
try {
|
|
1114
1252
|
const lastValid = this.positiveCache.get(conn.connectionId);
|
|
1115
1253
|
if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
|
|
@@ -1148,7 +1286,7 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1148
1286
|
tenantId: conn.tenantId,
|
|
1149
1287
|
roles: conn.originalAuth.roles,
|
|
1150
1288
|
metadata: conn.originalAuth.metadata,
|
|
1151
|
-
transport:
|
|
1289
|
+
transport: conn.transport,
|
|
1152
1290
|
ip: conn.ip,
|
|
1153
1291
|
userAgent: conn.userAgent,
|
|
1154
1292
|
connectedAt: conn.connectedAt
|
|
@@ -1678,9 +1816,11 @@ exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
|
|
|
1678
1816
|
exports.ROOM_PREFIXES = ROOM_PREFIXES;
|
|
1679
1817
|
exports.RedisOfflineQueue = RedisOfflineQueue;
|
|
1680
1818
|
exports.RedisRealtimePubSub = RedisRealtimePubSub;
|
|
1819
|
+
exports.assertIdentityIsNotBlank = assertIdentityIsNotBlank;
|
|
1681
1820
|
exports.composeForRoot = composeForRoot;
|
|
1682
1821
|
exports.composeForRootAsync = composeForRootAsync;
|
|
1683
1822
|
exports.composeRoomId = composeRoomId;
|
|
1684
1823
|
exports.createSseController = createSseController;
|
|
1685
1824
|
exports.parseCookieHeader = parseCookieHeader;
|
|
1825
|
+
exports.resolveAuthTenant = resolveAuthTenant;
|
|
1686
1826
|
exports.sseWiring = sseWiring;
|
|
@@ -47,10 +47,10 @@ interface ConnectionAuthContext {
|
|
|
47
47
|
/**
|
|
48
48
|
* Query string parameters — useful for the ticket pattern.
|
|
49
49
|
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
50
|
+
* On WebSocket a repeated key (`?a=1&a=2`) arrives as a `string[]`, except the
|
|
51
|
+
* `ticket` parameter, which the gateway collapses to a single string. On SSE only
|
|
52
|
+
* a single string value is kept; a repeated key arrives as `undefined`.
|
|
53
|
+
* Authenticators that expect a single value should check `typeof value === 'string'`.
|
|
54
54
|
*/
|
|
55
55
|
readonly query: Record<string, string | string[] | undefined>;
|
|
56
56
|
/**
|
|
@@ -69,7 +69,20 @@ interface ConnectionAuthContext {
|
|
|
69
69
|
* may carry extra fields through the `metadata` bag.
|
|
70
70
|
*/
|
|
71
71
|
interface AuthenticationResult {
|
|
72
|
+
/**
|
|
73
|
+
* The authenticated account. Must be a non-empty string: a blank one indexes
|
|
74
|
+
* every such connection under a single key and joins them all to the room
|
|
75
|
+
* `user:`, so it is refused at connection bootstrap rather than registered.
|
|
76
|
+
*/
|
|
72
77
|
readonly userId: string;
|
|
78
|
+
/**
|
|
79
|
+
* The tenant this connection routes on, or absent when it belongs to none.
|
|
80
|
+
*
|
|
81
|
+
* Absent and empty are different. Omitting it — or returning `undefined` or
|
|
82
|
+
* `null` — means no tenant: indexed under none, joining no tenant room. An empty
|
|
83
|
+
* or whitespace-only string is refused, because it is a shared bucket rather than
|
|
84
|
+
* a missing value: every connection carrying `''` lands under the same key.
|
|
85
|
+
*/
|
|
73
86
|
readonly tenantId?: string;
|
|
74
87
|
readonly roles?: readonly string[];
|
|
75
88
|
/**
|
|
@@ -110,6 +123,12 @@ interface IConnectionAuthenticator {
|
|
|
110
123
|
*
|
|
111
124
|
* @returns the authenticated result, or `null` to reject the connection (the
|
|
112
125
|
* transport replies 401 / disconnects accordingly).
|
|
126
|
+
*
|
|
127
|
+
* Returning a result whose `userId` is blank, or whose `tenantId` is present but
|
|
128
|
+
* blank, is not a second way to reject: it is a contract violation. The connection
|
|
129
|
+
* is refused either way, but it surfaces as a server fault rather than a 401,
|
|
130
|
+
* because the credentials were accepted and the fault is in this method. Return
|
|
131
|
+
* `null` to reject a client.
|
|
113
132
|
*/
|
|
114
133
|
authenticate(context: ConnectionAuthContext): Promise<AuthenticationResult | null>;
|
|
115
134
|
/**
|
|
@@ -328,7 +347,17 @@ interface ReauthenticationPolicy {
|
|
|
328
347
|
interface BymaxRealtimeModuleOptions {
|
|
329
348
|
transport: TransportMode;
|
|
330
349
|
authenticator: IConnectionAuthenticator;
|
|
331
|
-
|
|
350
|
+
/**
|
|
351
|
+
* Derive the tenant a connection routes on from the authenticated result.
|
|
352
|
+
*
|
|
353
|
+
* Applied on **both** transports. `undefined` and `null` both mean "no opinion"
|
|
354
|
+
* and fall back to `auth.tenantId` rather than clearing it; to place a connection
|
|
355
|
+
* in no tenant, return a result without one from the authenticator. `null` is in
|
|
356
|
+
* the signature because the implementation accepts it and a type narrower than the
|
|
357
|
+
* behaviour forces a cast on anyone testing the boundary. A blank string is
|
|
358
|
+
* refused, on the same terms as `AuthenticationResult.tenantId`.
|
|
359
|
+
*/
|
|
360
|
+
tenantResolver?: (auth: AuthenticationResult) => string | undefined | null;
|
|
332
361
|
hooks?: IConnectionLifecycleHooks;
|
|
333
362
|
pubsub?: IRealtimePubSub;
|
|
334
363
|
offlineQueue?: IOfflineQueueStorage;
|
|
@@ -619,9 +648,17 @@ declare class ConnectionRegistry {
|
|
|
619
648
|
private readonly byId;
|
|
620
649
|
private readonly byUserId;
|
|
621
650
|
private readonly byTenantId;
|
|
622
|
-
/**
|
|
651
|
+
/**
|
|
652
|
+
* Register a connection and index it by user and tenant.
|
|
653
|
+
*
|
|
654
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
655
|
+
*/
|
|
623
656
|
register(record: ConnectionRecord): void;
|
|
624
|
-
/**
|
|
657
|
+
/**
|
|
658
|
+
* Remove a connection from every index. Returns the removed record, if any.
|
|
659
|
+
*
|
|
660
|
+
* @internal Transport bookkeeping: applications must not call it.
|
|
661
|
+
*/
|
|
625
662
|
unregister(connectionId: string): ConnectionRecord | undefined;
|
|
626
663
|
/** Look up a single connection by id. */
|
|
627
664
|
get(connectionId: string): ConnectionRecord | undefined;
|
|
@@ -740,7 +777,13 @@ declare class RealtimeService {
|
|
|
740
777
|
emitToRoom(roomId: string, event: string, data: unknown): Promise<void>;
|
|
741
778
|
/** Send to every connected client. Use sparingly. */
|
|
742
779
|
broadcast(event: string, data: unknown): Promise<void>;
|
|
743
|
-
/**
|
|
780
|
+
/**
|
|
781
|
+
* Add a specific connection to a room.
|
|
782
|
+
*
|
|
783
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
784
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
785
|
+
* receives that tenant's events.
|
|
786
|
+
*/
|
|
744
787
|
joinRoom(connectionId: string, roomId: string): Promise<void>;
|
|
745
788
|
/** Remove a specific connection from a room. */
|
|
746
789
|
leaveRoom(connectionId: string, roomId: string): Promise<void>;
|
|
@@ -754,8 +797,8 @@ declare class RealtimeService {
|
|
|
754
797
|
*/
|
|
755
798
|
|
|
756
799
|
/**
|
|
757
|
-
* Periodically revalidates active
|
|
758
|
-
* `IConnectionAuthenticator.revalidate` contract.
|
|
800
|
+
* Periodically revalidates every active connection, on both transports, through the
|
|
801
|
+
* consumer-provided `IConnectionAuthenticator.revalidate` contract.
|
|
759
802
|
*
|
|
760
803
|
* A short positive cache (default 60 s) avoids hammering the auth backend on every
|
|
761
804
|
* interval tick. On failure the service either disconnects immediately or first emits
|
|
@@ -791,7 +834,7 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
|
|
|
791
834
|
*/
|
|
792
835
|
onApplicationShutdown(): void;
|
|
793
836
|
/**
|
|
794
|
-
* Run one revalidation cycle over
|
|
837
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
795
838
|
*
|
|
796
839
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
797
840
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1136,7 +1179,32 @@ declare class SseSubscriptionHandler {
|
|
|
1136
1179
|
private readonly hooks?;
|
|
1137
1180
|
private readonly offlineDelivery?;
|
|
1138
1181
|
private readonly logger;
|
|
1182
|
+
private readonly authenticated;
|
|
1139
1183
|
constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
|
|
1184
|
+
/**
|
|
1185
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
1186
|
+
*
|
|
1187
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
1188
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
1189
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
1190
|
+
* use would validate nothing.
|
|
1191
|
+
*
|
|
1192
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
1193
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
1194
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
1195
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
1196
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
1197
|
+
*
|
|
1198
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
1199
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
1200
|
+
* without a message.
|
|
1201
|
+
*
|
|
1202
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
1203
|
+
* @returns The same result with the routing tenant resolved.
|
|
1204
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
1205
|
+
* but blank.
|
|
1206
|
+
*/
|
|
1207
|
+
private resolveAndValidateIdentity;
|
|
1140
1208
|
/**
|
|
1141
1209
|
* Handle an incoming SSE connection request end-to-end.
|
|
1142
1210
|
*
|
|
@@ -1148,9 +1216,26 @@ declare class SseSubscriptionHandler {
|
|
|
1148
1216
|
* @param req - The incoming request (SSE GET).
|
|
1149
1217
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
1150
1218
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
1151
|
-
* @throws UnauthorizedException when authentication returns null
|
|
1219
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
1220
|
+
* credentials were rejected, which is a 401.
|
|
1221
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
1222
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
1223
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
1224
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
1225
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
1226
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
1227
|
+
* written to the server log.
|
|
1152
1228
|
*/
|
|
1153
1229
|
handle(req: SseRequest, res: SseResponse): Promise<Observable<MessageEvent>>;
|
|
1230
|
+
private openStream;
|
|
1231
|
+
/**
|
|
1232
|
+
* Authenticate ahead of the route, from a guard: with an interceptor registered Nest commits
|
|
1233
|
+
* `200` on the next macrotask, so a refusal that needs I/O is a status only if it comes first.
|
|
1234
|
+
*/
|
|
1235
|
+
authenticateBeforeCommit(req: SseRequest): Promise<void>;
|
|
1236
|
+
private toClientError;
|
|
1237
|
+
private serverError;
|
|
1238
|
+
private authenticateRequest;
|
|
1154
1239
|
/**
|
|
1155
1240
|
* Build the live Observable using a subscribe-before-register pattern.
|
|
1156
1241
|
*
|
|
@@ -1376,6 +1461,45 @@ declare class RedisOfflineQueue implements IOfflineQueueStorage {
|
|
|
1376
1461
|
acknowledge(userId: string, upToId: string): Promise<void>;
|
|
1377
1462
|
}
|
|
1378
1463
|
|
|
1464
|
+
/**
|
|
1465
|
+
* Resolve the tenant a connection routes on, and normalize a nullish result.
|
|
1466
|
+
*
|
|
1467
|
+
* Both transports must resolve the routing tenant through this one function. Two
|
|
1468
|
+
* copies of the rule can disagree, and a connection routed on one tenant by SSE and
|
|
1469
|
+
* another by WebSocket is a delivery to the wrong audience.
|
|
1470
|
+
*
|
|
1471
|
+
* `null` normalizes to `undefined` rather than passing through. `ConnectionRegistry`
|
|
1472
|
+
* guards on `!== undefined`, so a `null` tenant would otherwise be indexed under
|
|
1473
|
+
* `null` and compose the room `tenant:null` — the same shared-bucket defect as the
|
|
1474
|
+
* empty string, in a value a JWT claim produces routinely.
|
|
1475
|
+
*
|
|
1476
|
+
* @param options - The module options, read for an optional `tenantResolver`.
|
|
1477
|
+
* @param auth - The authentication result the consumer's authenticator returned.
|
|
1478
|
+
* @returns The same result with `tenantId` resolved, or absent when there is none.
|
|
1479
|
+
*/
|
|
1480
|
+
declare function resolveAuthTenant(options: Pick<BymaxRealtimeModuleOptions, 'tenantResolver'>, auth: AuthenticationResult): AuthenticationResult;
|
|
1481
|
+
/**
|
|
1482
|
+
* Reject an authentication result whose identity traits are present but blank.
|
|
1483
|
+
*
|
|
1484
|
+
* `userId` and `tenantId` index the registry and compose the `user:` and `tenant:`
|
|
1485
|
+
* rooms, so a blank one is not a missing value — it is a shared bucket. Every
|
|
1486
|
+
* connection whose authenticator returned `''` lands under the same key and joins
|
|
1487
|
+
* the same room, and a later emit to that key reaches all of them. On a long-lived
|
|
1488
|
+
* subscription that is not one wrong response but a stream that keeps delivering
|
|
1489
|
+
* for the life of the connection.
|
|
1490
|
+
*
|
|
1491
|
+
* An absent `tenantId` stays valid and means exactly what it says: this connection
|
|
1492
|
+
* belongs to no tenant, so it is indexed under none and joins no tenant room. The
|
|
1493
|
+
* distinction drawn is between *absent* and *empty*, and only the second is refused.
|
|
1494
|
+
*
|
|
1495
|
+
* Whitespace counts as blank. `' '` composes `user: ` and indexes under `' '`, which
|
|
1496
|
+
* is the same defect wearing a different character.
|
|
1497
|
+
*
|
|
1498
|
+
* @param auth - The resolved authentication result, after `resolveAuthTenant`.
|
|
1499
|
+
* @throws Error carrying `REALTIME_AUTH_FAILED` when a trait is present but blank.
|
|
1500
|
+
*/
|
|
1501
|
+
declare function assertIdentityIsNotBlank(auth: AuthenticationResult): void;
|
|
1502
|
+
|
|
1379
1503
|
/**
|
|
1380
1504
|
* @fileoverview Canonical room id prefixes for scoping emits and auto-join.
|
|
1381
1505
|
* @layer shared
|
|
@@ -1408,7 +1532,13 @@ type RoomPrefix = (typeof ROOM_PREFIXES)[keyof typeof ROOM_PREFIXES];
|
|
|
1408
1532
|
* Build a canonical room id following the library's prefix convention.
|
|
1409
1533
|
*
|
|
1410
1534
|
* Validation of the parts (e.g. non-empty ids) is the caller's responsibility —
|
|
1411
|
-
* this helper only joins the prefix and parts with
|
|
1535
|
+
* this helper only joins the prefix and parts with `:` and escapes nothing, so a
|
|
1536
|
+
* part must not contain `:`. `('a:b', 'c')` and `('a', 'b:c')` both give
|
|
1537
|
+
* `resource:a:b:c`; encode parts that come from outside with `encodeURIComponent`, which escapes `:` and so
|
|
1538
|
+
* is sound for this `:` separator only.
|
|
1539
|
+
*
|
|
1540
|
+
* A `RESOURCE` room carries no tenant. When ids are only unique within one, pass
|
|
1541
|
+
* the tenant as its own encoded part rather than gluing it to the id.
|
|
1412
1542
|
*
|
|
1413
1543
|
* @example
|
|
1414
1544
|
* ```ts
|
|
@@ -1539,4 +1669,4 @@ declare const REALTIME_ERROR_CODES: {
|
|
|
1539
1669
|
/** Union of canonical error code values. */
|
|
1540
1670
|
type RealtimeErrorCode = (typeof REALTIME_ERROR_CODES)[keyof typeof REALTIME_ERROR_CODES];
|
|
1541
1671
|
|
|
1542
|
-
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, sseWiring };
|
|
1672
|
+
export { type AuthenticationResult, BymaxRealtimeModule, type BymaxRealtimeModuleAsyncOptions, type BymaxRealtimeModuleOptions, type BymaxRealtimeModuleOptionsFactory, type ConnectionAuthContext, type ConnectionEventMeta, ConnectionRegistry, type CorsConfig, EventIdGenerator, EventReplayBuffer, HeartbeatService, type IConnectionAuthenticator, type IConnectionLifecycleHooks, type IOfflineQueueStorage, type IPresenceStorage, type IRealtimePubSub, type ITransport, InMemoryPubSub, OfflineQueueDeliveryService, type OfflineQueuedEvent, type PublicConnectionMeta, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, type RealtimeErrorCode, type RealtimeEvent, type RealtimePubSubMessage, RealtimePubSubSubscriber, RealtimeService, type ReauthenticationPolicy, ReauthenticationService, RedisOfflineQueue, type RedisOfflineQueueOptions, RedisRealtimePubSub, type RedisRealtimePubSubOptions, type ReservedEventName, type RoomPrefix, RoomRegistry, type SseOptions, type SseRealtimeModuleAsyncOptions, type SseRealtimeModuleOptions, SseSubscriptionHandler, SseTransport, type TransportMode, type TransportRegistration, type TransportWiring, type WebSocketOptions, type WebSocketRealtimeModuleAsyncOptions, type WebSocketRealtimeModuleOptions, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, parseCookieHeader, resolveAuthTenant, sseWiring };
|