@bymax-one/nest-realtime 1.1.2 → 1.2.1
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 +148 -1
- package/README.md +125 -14
- package/dist/internal/index.cjs +139 -18
- package/dist/internal/index.d.cts +196 -24
- package/dist/internal/index.d.ts +196 -24
- package/dist/internal/index.mjs +139 -20
- package/dist/websocket/index.cjs +59 -29
- package/dist/websocket/index.d.cts +21 -4
- package/dist/websocket/index.d.ts +21 -4
- package/dist/websocket/index.mjs +60 -30
- 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);
|
|
@@ -504,7 +529,8 @@ exports.SseTransport = class SseTransport {
|
|
|
504
529
|
originalAuth: {
|
|
505
530
|
userId: params.auth.userId,
|
|
506
531
|
tenantId: params.auth.tenantId,
|
|
507
|
-
roles: params.auth.roles
|
|
532
|
+
roles: params.auth.roles,
|
|
533
|
+
metadata: params.auth.metadata
|
|
508
534
|
}
|
|
509
535
|
};
|
|
510
536
|
this.connections.register(record);
|
|
@@ -526,6 +552,7 @@ exports.SseTransport = class SseTransport {
|
|
|
526
552
|
userId: record.userId,
|
|
527
553
|
tenantId: record.tenantId,
|
|
528
554
|
roles: record.originalAuth.roles,
|
|
555
|
+
metadata: record.originalAuth.metadata,
|
|
529
556
|
transport: "sse",
|
|
530
557
|
ip: record.ip,
|
|
531
558
|
userAgent: record.userAgent,
|
|
@@ -763,6 +790,7 @@ function buildMeta(record) {
|
|
|
763
790
|
userId: record.userId,
|
|
764
791
|
tenantId: record.tenantId,
|
|
765
792
|
roles: record.originalAuth.roles,
|
|
793
|
+
metadata: record.originalAuth.metadata,
|
|
766
794
|
transport: "sse",
|
|
767
795
|
ip: record.ip,
|
|
768
796
|
userAgent: record.userAgent,
|
|
@@ -783,6 +811,39 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
783
811
|
hooks;
|
|
784
812
|
offlineDelivery;
|
|
785
813
|
logger = new common.Logger(exports.SseSubscriptionHandler.name);
|
|
814
|
+
/**
|
|
815
|
+
* Resolve the tenant this connection routes on, and refuse a blank identity.
|
|
816
|
+
*
|
|
817
|
+
* Both transports resolve the routing tenant through this one function, so a
|
|
818
|
+
* connection carries the same tenant whichever one opened it. The check runs on
|
|
819
|
+
* the resolved value rather than the raw one — validating what the server does not
|
|
820
|
+
* use would validate nothing.
|
|
821
|
+
*
|
|
822
|
+
* A blank identity is the consumer's configuration rather than the client's
|
|
823
|
+
* credentials, so it is deliberately not a 401: a 401 would tell a client its
|
|
824
|
+
* credentials were rejected when they were accepted, inviting a retry that cannot
|
|
825
|
+
* succeed. Wrapped rather than rethrown raw so the 500 is a decision Nest logs
|
|
826
|
+
* once, not an unhandled crash logging a stack on every reconnect.
|
|
827
|
+
*
|
|
828
|
+
* The reason names the operator's fix, so it goes to the server log and the client
|
|
829
|
+
* receives Nest's generic 500 body, as the WebSocket gateway does by disconnecting
|
|
830
|
+
* without a message.
|
|
831
|
+
*
|
|
832
|
+
* @param auth - The result the consumer's authenticator returned.
|
|
833
|
+
* @returns The same result with the routing tenant resolved.
|
|
834
|
+
* @throws InternalServerErrorException with the generic body when a trait is present
|
|
835
|
+
* but blank.
|
|
836
|
+
*/
|
|
837
|
+
resolveAndValidateIdentity(auth) {
|
|
838
|
+
const resolvedAuth = resolveAuthTenant(this.options, auth);
|
|
839
|
+
try {
|
|
840
|
+
assertIdentityIsNotBlank(resolvedAuth);
|
|
841
|
+
} catch (err) {
|
|
842
|
+
this.logger.error(`SSE connection refused \u2014 responding 500: ${err.message}`);
|
|
843
|
+
throw new common.InternalServerErrorException();
|
|
844
|
+
}
|
|
845
|
+
return resolvedAuth;
|
|
846
|
+
}
|
|
786
847
|
/**
|
|
787
848
|
* Handle an incoming SSE connection request end-to-end.
|
|
788
849
|
*
|
|
@@ -794,7 +855,15 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
794
855
|
* @param req - The incoming request (SSE GET).
|
|
795
856
|
* @param res - The response (passthrough for header mutations and heartbeat writes).
|
|
796
857
|
* @returns An Observable of `MessageEvent` values for NestJS `@Sse` to stream.
|
|
797
|
-
* @throws UnauthorizedException when authentication returns null
|
|
858
|
+
* @throws UnauthorizedException when authentication returns null — the client's
|
|
859
|
+
* credentials were rejected, which is a 401.
|
|
860
|
+
* @throws InternalServerErrorException when the authenticator, or the configured
|
|
861
|
+
* `tenantResolver`, yields a blank `userId` or `tenantId`. This is deliberately not
|
|
862
|
+
* a 401: the credentials were accepted and the fault is the consumer's
|
|
863
|
+
* configuration, so it surfaces as a 500 rather than telling a client to retry
|
|
864
|
+
* something that cannot succeed. The exception carries no message, so the client
|
|
865
|
+
* gets Nest's generic body, and the `REALTIME_AUTH_FAILED` reason naming the fix is
|
|
866
|
+
* written to the server log.
|
|
798
867
|
*/
|
|
799
868
|
async handle(req, res) {
|
|
800
869
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
@@ -802,8 +871,7 @@ exports.SseSubscriptionHandler = class SseSubscriptionHandler {
|
|
|
802
871
|
const context = buildAuthContext(req);
|
|
803
872
|
const auth = await this.transport.authenticate(context);
|
|
804
873
|
if (!auth) throw new common.UnauthorizedException(REALTIME_ERROR_CODES.AUTH_FAILED);
|
|
805
|
-
const
|
|
806
|
-
const resolvedAuth = resolvedTenantId !== void 0 ? { ...auth, tenantId: resolvedTenantId } : auth;
|
|
874
|
+
const resolvedAuth = this.resolveAndValidateIdentity(auth);
|
|
807
875
|
const connectionId = crypto.randomUUID();
|
|
808
876
|
const subject = new rxjs.Subject();
|
|
809
877
|
const close$ = new rxjs.Subject();
|
|
@@ -929,9 +997,14 @@ exports.SseSubscriptionHandler = __decorateClass([
|
|
|
929
997
|
__decorateParam(4, common.Inject(exports.OfflineQueueDeliveryService))
|
|
930
998
|
], exports.SseSubscriptionHandler);
|
|
931
999
|
|
|
1000
|
+
// src/server/utils/normalize-endpoint-path.ts
|
|
1001
|
+
function normalizeEndpointPath(endpoint) {
|
|
1002
|
+
return endpoint.startsWith("/") ? endpoint.slice(1) : endpoint;
|
|
1003
|
+
}
|
|
1004
|
+
|
|
932
1005
|
// src/server/factories/sse-controller.factory.ts
|
|
933
1006
|
function createSseController(endpoint) {
|
|
934
|
-
const ssePath =
|
|
1007
|
+
const ssePath = normalizeEndpointPath(endpoint);
|
|
935
1008
|
let DynamicSseController = class {
|
|
936
1009
|
// Explicit @Inject: the published bundle is built by esbuild/tsup, which does
|
|
937
1010
|
// not emit `design:paramtypes` decorator metadata, so constructor params must
|
|
@@ -1021,7 +1094,13 @@ exports.RealtimeService = class RealtimeService {
|
|
|
1021
1094
|
broadcast(event, data) {
|
|
1022
1095
|
return this.transport.broadcast(event, data);
|
|
1023
1096
|
}
|
|
1024
|
-
/**
|
|
1097
|
+
/**
|
|
1098
|
+
* Add a specific connection to a room.
|
|
1099
|
+
*
|
|
1100
|
+
* The room id is not checked. Never pass client-supplied input that could start
|
|
1101
|
+
* with the reserved `user:` or `tenant:` prefixes: joining `tenant:<other>`
|
|
1102
|
+
* receives that tenant's events.
|
|
1103
|
+
*/
|
|
1025
1104
|
joinRoom(connectionId, roomId) {
|
|
1026
1105
|
return this.transport.joinRoom(connectionId, roomId);
|
|
1027
1106
|
}
|
|
@@ -1091,7 +1170,7 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1091
1170
|
this.positiveCache.clear();
|
|
1092
1171
|
}
|
|
1093
1172
|
/**
|
|
1094
|
-
* Run one revalidation cycle over
|
|
1173
|
+
* Run one revalidation cycle over every active connection, SSE and WebSocket alike.
|
|
1095
1174
|
*
|
|
1096
1175
|
* A cache hit within `cacheTtlMs` skips the `revalidate` call. A positive result
|
|
1097
1176
|
* refreshes the cache. A negative result (or a thrown error) invokes the configured
|
|
@@ -1101,14 +1180,19 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1101
1180
|
*/
|
|
1102
1181
|
async runCycle() {
|
|
1103
1182
|
const now = Date.now();
|
|
1104
|
-
|
|
1183
|
+
const connections = [
|
|
1184
|
+
...this.connections.allByTransport("sse"),
|
|
1185
|
+
...this.connections.allByTransport("websocket")
|
|
1186
|
+
];
|
|
1187
|
+
for (const conn of connections) {
|
|
1105
1188
|
try {
|
|
1106
1189
|
const lastValid = this.positiveCache.get(conn.connectionId);
|
|
1107
1190
|
if (lastValid !== void 0 && now - lastValid < this.policy.cacheTtlMs) continue;
|
|
1108
1191
|
const originalAuth = {
|
|
1109
1192
|
userId: conn.originalAuth.userId,
|
|
1110
1193
|
...conn.originalAuth.tenantId !== void 0 ? { tenantId: conn.originalAuth.tenantId } : {},
|
|
1111
|
-
...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {}
|
|
1194
|
+
...conn.originalAuth.roles !== void 0 ? { roles: conn.originalAuth.roles } : {},
|
|
1195
|
+
...conn.originalAuth.metadata !== void 0 ? { metadata: conn.originalAuth.metadata } : {}
|
|
1112
1196
|
};
|
|
1113
1197
|
const rawResult = await this.auth.revalidate?.(conn.connectionId, originalAuth) ?? true;
|
|
1114
1198
|
if (rawResult === true) {
|
|
@@ -1138,7 +1222,8 @@ exports.ReauthenticationService = class ReauthenticationService {
|
|
|
1138
1222
|
userId: conn.userId,
|
|
1139
1223
|
tenantId: conn.tenantId,
|
|
1140
1224
|
roles: conn.originalAuth.roles,
|
|
1141
|
-
|
|
1225
|
+
metadata: conn.originalAuth.metadata,
|
|
1226
|
+
transport: conn.transport,
|
|
1142
1227
|
ip: conn.ip,
|
|
1143
1228
|
userAgent: conn.userAgent,
|
|
1144
1229
|
connectedAt: conn.connectedAt
|
|
@@ -1160,6 +1245,7 @@ exports.ReauthenticationService = __decorateClass([
|
|
|
1160
1245
|
], exports.ReauthenticationService);
|
|
1161
1246
|
|
|
1162
1247
|
// src/server/composition/realtime-module.factory.ts
|
|
1248
|
+
var DEFAULT_ASYNC_SSE_ENDPOINT = "/events";
|
|
1163
1249
|
var EXPORTED_TOKENS = [
|
|
1164
1250
|
exports.RealtimeService,
|
|
1165
1251
|
exports.ConnectionRegistry,
|
|
@@ -1224,6 +1310,20 @@ function composeForRoot(moduleClass, wiring, logger, options) {
|
|
|
1224
1310
|
exports: EXPORTED_TOKENS
|
|
1225
1311
|
};
|
|
1226
1312
|
}
|
|
1313
|
+
function assertSseEndpointApplies(asyncOptions, moduleName) {
|
|
1314
|
+
if (asyncOptions.sseEndpoint === void 0 || asyncOptions.transport !== "websocket") return;
|
|
1315
|
+
throw new Error(
|
|
1316
|
+
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: sseEndpoint '${asyncOptions.sseEndpoint}' was set but transport 'websocket' registers no SSE controller \u2014 use 'both' to serve SSE too`
|
|
1317
|
+
);
|
|
1318
|
+
}
|
|
1319
|
+
function bindSseEndpoint(resolved, declared, bound, moduleName) {
|
|
1320
|
+
if (declared !== void 0 && normalizeEndpointPath(declared) !== normalizeEndpointPath(bound)) {
|
|
1321
|
+
throw new Error(
|
|
1322
|
+
`[${moduleName}] ${REALTIME_ERROR_CODES.INVALID_OPTIONS}: the factory resolved sse.endpoint '${declared}' but forRootAsync bound the SSE route to '${bound}' \u2014 controllers are registered before the factory runs, so declare the path as 'sseEndpoint' on the forRootAsync registration itself`
|
|
1323
|
+
);
|
|
1324
|
+
}
|
|
1325
|
+
return Object.freeze({ ...resolved, sse: { ...resolved.sse, endpoint: bound } });
|
|
1326
|
+
}
|
|
1227
1327
|
function resolveAsyncOptions(raw, declaredMode, instanceId, source, logger, moduleName) {
|
|
1228
1328
|
if (!raw) {
|
|
1229
1329
|
throw new Error(`${REALTIME_ERROR_CODES.INVALID_OPTIONS}: ${source} returned nothing`);
|
|
@@ -1251,9 +1351,22 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
1251
1351
|
);
|
|
1252
1352
|
}
|
|
1253
1353
|
assertModeSupported(wiring, asyncOptions.transport, moduleName);
|
|
1354
|
+
assertSseEndpointApplies(asyncOptions, moduleName);
|
|
1254
1355
|
const FACTORY_TOKEN = /* @__PURE__ */ Symbol("REALTIME_OPTIONS_FACTORY");
|
|
1255
1356
|
const instanceId = crypto.randomUUID();
|
|
1256
|
-
const
|
|
1357
|
+
const boundSseEndpoint = asyncOptions.sseEndpoint ?? DEFAULT_ASYNC_SSE_ENDPOINT;
|
|
1358
|
+
const resolve = (raw, source) => {
|
|
1359
|
+
const resolved = resolveAsyncOptions(
|
|
1360
|
+
raw,
|
|
1361
|
+
asyncOptions.transport,
|
|
1362
|
+
instanceId,
|
|
1363
|
+
source,
|
|
1364
|
+
logger,
|
|
1365
|
+
moduleName
|
|
1366
|
+
);
|
|
1367
|
+
if (asyncOptions.transport === "websocket") return resolved;
|
|
1368
|
+
return bindSseEndpoint(resolved, raw?.sse?.endpoint, boundSseEndpoint, moduleName);
|
|
1369
|
+
};
|
|
1257
1370
|
const resolvedOptionsProvider = asyncOptions.useFactory ? {
|
|
1258
1371
|
provide: REALTIME_OPTIONS_TOKEN,
|
|
1259
1372
|
useFactory: async (...args) => resolve(await asyncOptions.useFactory(...args), "useFactory"),
|
|
@@ -1268,7 +1381,10 @@ function composeForRootAsync(moduleClass, wiring, logger, asyncOptions) {
|
|
|
1268
1381
|
};
|
|
1269
1382
|
const factoryClassProvider = asyncOptions.useClass ? [{ provide: FACTORY_TOKEN, useClass: asyncOptions.useClass }] : [];
|
|
1270
1383
|
const fromOptions = (token, read) => ({ provide: token, useFactory: read, inject: [REALTIME_OPTIONS_TOKEN] });
|
|
1271
|
-
const { providers: transportProviders, controllers } = wiring.buildAsync(
|
|
1384
|
+
const { providers: transportProviders, controllers } = wiring.buildAsync({
|
|
1385
|
+
mode: asyncOptions.transport,
|
|
1386
|
+
sseEndpoint: boundSseEndpoint
|
|
1387
|
+
});
|
|
1272
1388
|
return {
|
|
1273
1389
|
module: moduleClass,
|
|
1274
1390
|
imports: asyncOptions.imports ?? [],
|
|
@@ -1369,7 +1485,6 @@ exports.RealtimePubSubSubscriber = __decorateClass([
|
|
|
1369
1485
|
], exports.RealtimePubSubSubscriber);
|
|
1370
1486
|
|
|
1371
1487
|
// src/server/composition/sse-wiring.ts
|
|
1372
|
-
var DEFAULT_ASYNC_ENDPOINT = "/events";
|
|
1373
1488
|
var sseWiring = {
|
|
1374
1489
|
modes: ["sse"],
|
|
1375
1490
|
build(resolved) {
|
|
@@ -1384,7 +1499,7 @@ var sseWiring = {
|
|
|
1384
1499
|
gateways: []
|
|
1385
1500
|
};
|
|
1386
1501
|
},
|
|
1387
|
-
buildAsync() {
|
|
1502
|
+
buildAsync({ sseEndpoint }) {
|
|
1388
1503
|
return {
|
|
1389
1504
|
providers: [
|
|
1390
1505
|
exports.SseTransport,
|
|
@@ -1392,7 +1507,7 @@ var sseWiring = {
|
|
|
1392
1507
|
exports.RealtimePubSubSubscriber,
|
|
1393
1508
|
{ provide: REALTIME_TRANSPORT_TOKEN, useExisting: exports.SseTransport }
|
|
1394
1509
|
],
|
|
1395
|
-
controllers: [createSseController(
|
|
1510
|
+
controllers: [createSseController(sseEndpoint)]
|
|
1396
1511
|
};
|
|
1397
1512
|
}
|
|
1398
1513
|
};
|
|
@@ -1420,9 +1535,12 @@ exports.BymaxRealtimeModule = class BymaxRealtimeModule {
|
|
|
1420
1535
|
* configuration rejects at bootstrap and the application fails to start with
|
|
1421
1536
|
* a clear error.
|
|
1422
1537
|
*
|
|
1423
|
-
* Controllers are registered at decoration time, so
|
|
1424
|
-
*
|
|
1425
|
-
*
|
|
1538
|
+
* Controllers are registered at decoration time, so the SSE route comes from
|
|
1539
|
+
* `sseEndpoint` on the registration rather than from the `sse.endpoint` the
|
|
1540
|
+
* factory resolves — the factory has not run yet when the controller is
|
|
1541
|
+
* built. It defaults to `/events`, and a factory that resolves a disagreeing
|
|
1542
|
+
* `sse.endpoint` is rejected at bootstrap rather than silently served on
|
|
1543
|
+
* another path.
|
|
1426
1544
|
*
|
|
1427
1545
|
* @throws when no factory pattern is given, more than one is, or the factory
|
|
1428
1546
|
* resolves a transport other than `'sse'`.
|
|
@@ -1430,6 +1548,7 @@ exports.BymaxRealtimeModule = class BymaxRealtimeModule {
|
|
|
1430
1548
|
* ```ts
|
|
1431
1549
|
* BymaxRealtimeModule.forRootAsync({
|
|
1432
1550
|
* transport: 'sse',
|
|
1551
|
+
* sseEndpoint: '/realtime/sse', // optional; defaults to '/events'
|
|
1433
1552
|
* imports: [ConfigModule],
|
|
1434
1553
|
* inject: [ConfigService],
|
|
1435
1554
|
* useFactory: (cfg: ConfigService) => ({
|
|
@@ -1634,9 +1753,11 @@ exports.RESERVED_EVENT_NAMES = RESERVED_EVENT_NAMES;
|
|
|
1634
1753
|
exports.ROOM_PREFIXES = ROOM_PREFIXES;
|
|
1635
1754
|
exports.RedisOfflineQueue = RedisOfflineQueue;
|
|
1636
1755
|
exports.RedisRealtimePubSub = RedisRealtimePubSub;
|
|
1756
|
+
exports.assertIdentityIsNotBlank = assertIdentityIsNotBlank;
|
|
1637
1757
|
exports.composeForRoot = composeForRoot;
|
|
1638
1758
|
exports.composeForRootAsync = composeForRootAsync;
|
|
1639
1759
|
exports.composeRoomId = composeRoomId;
|
|
1640
1760
|
exports.createSseController = createSseController;
|
|
1641
1761
|
exports.parseCookieHeader = parseCookieHeader;
|
|
1762
|
+
exports.resolveAuthTenant = resolveAuthTenant;
|
|
1642
1763
|
exports.sseWiring = sseWiring;
|