@terreno/api 0.31.0 → 56.0.0-beta.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/dist/api.d.ts +10 -0
- package/dist/api.js +110 -361
- package/dist/auth.d.ts +26 -0
- package/dist/auth.js +121 -26
- package/dist/betterAuth.d.ts +5 -0
- package/dist/betterAuthSetup.js +23 -4
- package/dist/docLoader.js +12 -9
- package/dist/errors.d.ts +13 -0
- package/dist/errors.js +29 -1
- package/dist/index.d.ts +17 -1
- package/dist/index.js +29 -1
- package/dist/middleware.d.ts +7 -0
- package/dist/middleware.js +16 -1
- package/dist/openApiCompat.d.ts +10 -1
- package/dist/openApiCompat.js +115 -47
- package/dist/permissions.d.ts +27 -0
- package/dist/permissions.js +42 -1
- package/dist/plugins.d.ts +13 -0
- package/dist/plugins.js +47 -1
- package/dist/realtime/changeStreamWatcher.d.ts +100 -3
- package/dist/realtime/changeStreamWatcher.js +542 -137
- package/dist/realtime/realtimeApp.d.ts +2 -0
- package/dist/realtime/realtimeApp.js +83 -27
- package/dist/realtime/sessionRevalidation.d.ts +90 -0
- package/dist/realtime/sessionRevalidation.js +438 -0
- package/dist/realtime/socketAuth.d.ts +97 -0
- package/dist/realtime/socketAuth.js +272 -0
- package/dist/realtime/socketUser.d.ts +54 -0
- package/dist/realtime/socketUser.js +75 -5
- package/dist/realtime/types.d.ts +54 -0
- package/dist/secretProviders.d.ts +23 -0
- package/dist/secretProviders.js +9 -3
- package/dist/sync/executors.d.ts +198 -0
- package/dist/sync/executors.js +670 -0
- package/dist/sync/loadHarness.js +807 -0
- package/dist/sync/models.d.ts +216 -0
- package/dist/sync/models.js +644 -0
- package/dist/sync/mutationHandler.d.ts +97 -0
- package/dist/sync/mutationHandler.js +886 -0
- package/dist/sync/registry.d.ts +73 -0
- package/dist/sync/registry.js +223 -0
- package/dist/sync/routes.d.ts +62 -0
- package/dist/sync/routes.js +936 -0
- package/dist/sync/scripts/compactTombstones.d.ts +47 -0
- package/dist/sync/scripts/compactTombstones.js +270 -0
- package/dist/sync/serialize.d.ts +20 -0
- package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
- package/dist/sync/socketHandlers.d.ts +54 -0
- package/dist/sync/socketHandlers.js +470 -0
- package/dist/sync/streams.d.ts +85 -0
- package/dist/sync/streams.js +221 -0
- package/dist/sync/syncApp.d.ts +29 -0
- package/dist/sync/syncApp.js +44 -0
- package/dist/sync/syncBatch.d.ts +71 -0
- package/dist/sync/syncBatch.js +252 -0
- package/dist/sync/syncSeqPlugin.d.ts +8 -0
- package/dist/sync/syncSeqPlugin.js +899 -0
- package/dist/sync/types.d.ts +254 -0
- package/dist/sync/types.js +9 -0
- package/dist/terrenoApp.js +90 -27
- package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
- package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
- package/package.json +7 -6
- package/src/__tests__/openApiCompat.test.ts +20 -0
- package/src/api.errors.test.ts +32 -23
- package/src/api.test.ts +12 -0
- package/src/api.ts +87 -296
- package/src/auth.test.ts +202 -0
- package/src/auth.ts +134 -23
- package/src/betterAuth.ts +6 -0
- package/src/betterAuthSetup.test.ts +34 -0
- package/src/betterAuthSetup.ts +20 -1
- package/src/configuration.test.ts +59 -38
- package/src/configurationPlugin.test.ts +72 -42
- package/src/docLoader.ts +3 -1
- package/src/errors.ts +33 -0
- package/src/expressServer.test.ts +7 -1
- package/src/index.ts +42 -0
- package/src/middleware.test.ts +56 -1
- package/src/middleware.ts +15 -0
- package/src/openApiCompat.ts +99 -45
- package/src/permissions.test.ts +101 -17
- package/src/permissions.ts +49 -0
- package/src/plugins.test.ts +64 -0
- package/src/plugins.ts +56 -0
- package/src/realtime/changeStreamWatcher.ts +552 -114
- package/src/realtime/realtime.test.ts +157 -0
- package/src/realtime/realtimeApp.ts +82 -14
- package/src/realtime/realtimeAppSetup.test.ts +25 -27
- package/src/realtime/sessionRevalidation.test.ts +423 -0
- package/src/realtime/sessionRevalidation.ts +273 -0
- package/src/realtime/socketAuth.test.ts +355 -0
- package/src/realtime/socketAuth.ts +228 -0
- package/src/realtime/socketUser.ts +69 -0
- package/src/realtime/types.ts +54 -0
- package/src/secretProviders.test.ts +7 -1
- package/src/secretProviders.ts +15 -3
- package/src/secretProvidersGcpClient.test.ts +66 -0
- package/src/sync/ensureSyncIndexes.test.ts +144 -0
- package/src/sync/executors.test.ts +882 -0
- package/src/sync/executors.ts +705 -0
- package/src/sync/integration.test.ts +1160 -0
- package/src/sync/loadHarness.ts +618 -0
- package/src/sync/models.ts +641 -0
- package/src/sync/mutationHandler.test.ts +1252 -0
- package/src/sync/mutationHandler.ts +850 -0
- package/src/sync/registry.ts +232 -0
- package/src/sync/routes.ts +812 -0
- package/src/sync/scripts/compactTombstones.test.ts +249 -0
- package/src/sync/scripts/compactTombstones.ts +145 -0
- package/src/sync/serialize.ts +48 -0
- package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
- package/src/sync/socketHandlers.ts +320 -0
- package/src/sync/streams.ts +188 -0
- package/src/sync/sync.test.ts +582 -0
- package/src/sync/syncApp.ts +44 -0
- package/src/sync/syncBatch.ts +219 -0
- package/src/sync/syncFrontier.test.ts +494 -0
- package/src/sync/syncPhaseC.test.ts +718 -0
- package/src/sync/syncRoutes.test.ts +865 -0
- package/src/sync/syncSeqPlugin.ts +730 -0
- package/src/sync/syncSocket.test.ts +1440 -0
- package/src/sync/types.ts +270 -0
- package/src/terrenoApp.ts +37 -17
- package/src/tests/bunSetup.ts +8 -0
- package/tsconfig.json +4 -4
- package/tsconfig.typedoc.json +7 -1
- package/dist/__tests__/openApiCompat.test.js +0 -317
- package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
- package/dist/__tests__/versionCheckPlugin.test.js +0 -597
- package/dist/actions.openApi.test.d.ts +0 -1
- package/dist/actions.openApi.test.js +0 -253
- package/dist/actions.test.d.ts +0 -1
- package/dist/actions.test.js +0 -1087
- package/dist/api.arrayOperations.test.d.ts +0 -1
- package/dist/api.arrayOperations.test.js +0 -878
- package/dist/api.asyncHandler.test.d.ts +0 -1
- package/dist/api.asyncHandler.test.js +0 -236
- package/dist/api.coverage.test.d.ts +0 -1
- package/dist/api.coverage.test.js +0 -192
- package/dist/api.errorPaths.test.d.ts +0 -1
- package/dist/api.errorPaths.test.js +0 -887
- package/dist/api.errors.test.d.ts +0 -1
- package/dist/api.errors.test.js +0 -185
- package/dist/api.hooks.test.d.ts +0 -1
- package/dist/api.hooks.test.js +0 -950
- package/dist/api.query.test.d.ts +0 -1
- package/dist/api.query.test.js +0 -948
- package/dist/api.test.d.ts +0 -1
- package/dist/api.test.js +0 -2820
- package/dist/auth.compile.test.d.ts +0 -1
- package/dist/auth.compile.test.js +0 -201
- package/dist/auth.coverage.test.d.ts +0 -1
- package/dist/auth.coverage.test.js +0 -202
- package/dist/auth.test.d.ts +0 -1
- package/dist/auth.test.js +0 -2286
- package/dist/betterAuth.test.d.ts +0 -1
- package/dist/betterAuth.test.js +0 -181
- package/dist/betterAuthApp.test.d.ts +0 -1
- package/dist/betterAuthApp.test.js +0 -242
- package/dist/betterAuthSetup.test.d.ts +0 -1
- package/dist/betterAuthSetup.test.js +0 -762
- package/dist/config.test.d.ts +0 -1
- package/dist/config.test.js +0 -353
- package/dist/configuration.test.d.ts +0 -1
- package/dist/configuration.test.js +0 -980
- package/dist/configurationPlugin.test.d.ts +0 -1
- package/dist/configurationPlugin.test.js +0 -827
- package/dist/consentApp.test.d.ts +0 -1
- package/dist/consentApp.test.js +0 -1411
- package/dist/docLoader.test.d.ts +0 -1
- package/dist/docLoader.test.js +0 -137
- package/dist/envConfigurationPlugin.test.d.ts +0 -1
- package/dist/envConfigurationPlugin.test.js +0 -369
- package/dist/errors.test.d.ts +0 -1
- package/dist/errors.test.js +0 -607
- package/dist/expressServer.test.d.ts +0 -1
- package/dist/expressServer.test.js +0 -1249
- package/dist/githubAuth.test.d.ts +0 -1
- package/dist/githubAuth.test.js +0 -1142
- package/dist/httpClient.test.d.ts +0 -1
- package/dist/httpClient.test.js +0 -1471
- package/dist/logger.test.d.ts +0 -1
- package/dist/logger.test.js +0 -685
- package/dist/middleware.test.d.ts +0 -1
- package/dist/middleware.test.js +0 -241
- package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
- package/dist/notifiers/googleChatNotifier.test.js +0 -298
- package/dist/notifiers/slackNotifier.test.d.ts +0 -1
- package/dist/notifiers/slackNotifier.test.js +0 -297
- package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
- package/dist/notifiers/zoomNotifier.test.js +0 -373
- package/dist/openApi.test.d.ts +0 -1
- package/dist/openApi.test.js +0 -620
- package/dist/openApiBuilder.test.d.ts +0 -1
- package/dist/openApiBuilder.test.js +0 -599
- package/dist/openApiEtag.test.d.ts +0 -1
- package/dist/openApiEtag.test.js +0 -86
- package/dist/openApiValidator.test.d.ts +0 -1
- package/dist/openApiValidator.test.js +0 -795
- package/dist/permissions.middleware.test.d.ts +0 -1
- package/dist/permissions.middleware.test.js +0 -308
- package/dist/permissions.test.d.ts +0 -1
- package/dist/permissions.test.js +0 -439
- package/dist/plugins.test.d.ts +0 -1
- package/dist/plugins.test.js +0 -902
- package/dist/populate.test.d.ts +0 -1
- package/dist/populate.test.js +0 -370
- package/dist/realtime/realtime.test.d.ts +0 -10
- package/dist/realtime/realtime.test.js +0 -4213
- package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
- package/dist/realtime/realtimeAppSetup.test.js +0 -213
- package/dist/requestContext.test.d.ts +0 -1
- package/dist/requestContext.test.js +0 -412
- package/dist/scriptRunner.test.d.ts +0 -1
- package/dist/scriptRunner.test.js +0 -386
- package/dist/secretProviders.test.d.ts +0 -1
- package/dist/secretProviders.test.js +0 -726
- package/dist/syncConsents.test.d.ts +0 -1
- package/dist/syncConsents.test.js +0 -522
- package/dist/terrenoApp.test.d.ts +0 -1
- package/dist/terrenoApp.test.js +0 -489
- package/dist/tests/bunSetup.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
- package/dist/tests/fixtures/compileAuthEntry.js +0 -37
- package/dist/tests/testEnv.d.ts +0 -0
- package/dist/tests/testEnv.js +0 -6
- package/dist/transformers.test.d.ts +0 -1
- package/dist/transformers.test.js +0 -423
- package/dist/utils.test.d.ts +0 -1
- package/dist/utils.test.js +0 -242
- /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
|
@@ -69,8 +69,10 @@ export declare const installRealtimeSocketHandlers: (socket: RealtimeSocketLike,
|
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
71
71
|
export declare class RealtimeApp implements TerrenoPlugin {
|
|
72
|
+
private app;
|
|
72
73
|
private io;
|
|
73
74
|
private config;
|
|
75
|
+
private sessionRevalidation;
|
|
74
76
|
constructor(config?: RealtimeAppOptions);
|
|
75
77
|
/**
|
|
76
78
|
* Register routes and middleware. Adds a /realtime/health endpoint.
|
|
@@ -82,14 +82,18 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
|
82
82
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
83
83
|
exports.RealtimeApp = exports.installRealtimeSocketHandlers = exports.redactCredentials = exports.MAX_QUERY_SUBSCRIPTIONS = exports.MAX_DOCUMENT_SUBSCRIPTIONS = exports.MAX_MODEL_SUBSCRIPTIONS = void 0;
|
|
84
84
|
var Sentry = __importStar(require("@sentry/bun"));
|
|
85
|
-
var socketio_jwt_1 = require("@thream/socketio-jwt");
|
|
86
85
|
var socket_io_1 = require("socket.io");
|
|
87
86
|
var errors_1 = require("../errors");
|
|
88
87
|
var logger_1 = require("../logger");
|
|
89
88
|
var permissions_1 = require("../permissions");
|
|
89
|
+
var registry_1 = require("../sync/registry");
|
|
90
|
+
var socketHandlers_1 = require("../sync/socketHandlers");
|
|
91
|
+
var syncApp_1 = require("../sync/syncApp");
|
|
90
92
|
var changeStreamWatcher_1 = require("./changeStreamWatcher");
|
|
91
93
|
var queryStore_1 = require("./queryStore");
|
|
92
|
-
var
|
|
94
|
+
var registry_2 = require("./registry");
|
|
95
|
+
var sessionRevalidation_1 = require("./sessionRevalidation");
|
|
96
|
+
var socketAuth_1 = require("./socketAuth");
|
|
93
97
|
var socketUser_1 = require("./socketUser");
|
|
94
98
|
/**
|
|
95
99
|
* Caps on per-socket subscriptions. Prevents a malicious or buggy client from
|
|
@@ -178,7 +182,9 @@ var installRealtimeSocketHandlers = function (socket, options) {
|
|
|
178
182
|
var logInfo = (_a = options.logInfo) !== null && _a !== void 0 ? _a : (function () { });
|
|
179
183
|
var userId = (_b = socket.decodedToken) === null || _b === void 0 ? void 0 : _b.id;
|
|
180
184
|
var isAdmin = ((_c = socket.decodedToken) === null || _c === void 0 ? void 0 : _c.admin) === true;
|
|
181
|
-
|
|
185
|
+
// D2: re-derive per event rather than capturing once at install time, so a
|
|
186
|
+
// handshake-time-loaded full user (or one refreshed by D1's sweep) is always used.
|
|
187
|
+
var currentUser = function () { return (0, socketUser_1.getSocketUser)(socket); };
|
|
182
188
|
var counts = { document: 0, model: 0, query: 0 };
|
|
183
189
|
var joinUserRooms = function () { return __awaiter(void 0, void 0, void 0, function () {
|
|
184
190
|
return __generator(this, function (_a) {
|
|
@@ -218,7 +224,7 @@ var installRealtimeSocketHandlers = function (socket, options) {
|
|
|
218
224
|
logInfo("[realtime] User ".concat(userId, " hit model subscription limit"));
|
|
219
225
|
return [2 /*return*/];
|
|
220
226
|
}
|
|
221
|
-
entry = (0,
|
|
227
|
+
entry = (0, registry_2.findRegistryEntryByRoutePath)(modelName);
|
|
222
228
|
if (!entry) {
|
|
223
229
|
logInfo("[realtime] User ".concat(userId, " denied model subscription: collection \"").concat(modelName, "\" not registered"));
|
|
224
230
|
return [2 /*return*/];
|
|
@@ -231,7 +237,7 @@ var installRealtimeSocketHandlers = function (socket, options) {
|
|
|
231
237
|
"owner strategy restricts model room to admins");
|
|
232
238
|
return [2 /*return*/];
|
|
233
239
|
}
|
|
234
|
-
return [4 /*yield*/, canSubscribe(entry, "list",
|
|
240
|
+
return [4 /*yield*/, canSubscribe(entry, "list", currentUser())];
|
|
235
241
|
case 1:
|
|
236
242
|
if (!(_a.sent())) {
|
|
237
243
|
logInfo("[realtime] User ".concat(userId, " denied model subscription for ").concat(modelName, ": list permission denied"));
|
|
@@ -276,13 +282,13 @@ var installRealtimeSocketHandlers = function (socket, options) {
|
|
|
276
282
|
logInfo("[realtime] User ".concat(userId, " hit document subscription limit"));
|
|
277
283
|
return [2 /*return*/];
|
|
278
284
|
}
|
|
279
|
-
entry = (0,
|
|
285
|
+
entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
|
|
280
286
|
if (!entry) {
|
|
281
287
|
logInfo("[realtime] User ".concat(userId, " denied document subscription: ") +
|
|
282
288
|
"collection \"".concat(payload.collection, "\" not registered"));
|
|
283
289
|
return [2 /*return*/];
|
|
284
290
|
}
|
|
285
|
-
return [4 /*yield*/, canSubscribe(entry, "read",
|
|
291
|
+
return [4 /*yield*/, canSubscribe(entry, "read", currentUser())];
|
|
286
292
|
case 1:
|
|
287
293
|
if (!(_a.sent())) {
|
|
288
294
|
logInfo("[realtime] User ".concat(userId, " denied document subscription for ") +
|
|
@@ -337,13 +343,13 @@ var installRealtimeSocketHandlers = function (socket, options) {
|
|
|
337
343
|
logInfo("[realtime] User ".concat(userId, " hit query subscription limit"));
|
|
338
344
|
return [2 /*return*/];
|
|
339
345
|
}
|
|
340
|
-
entry = (0,
|
|
346
|
+
entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
|
|
341
347
|
if (!entry) {
|
|
342
348
|
logInfo("[realtime] User ".concat(userId, " denied query subscription: ") +
|
|
343
349
|
"collection \"".concat(payload.collection, "\" not registered"));
|
|
344
350
|
return [2 /*return*/];
|
|
345
351
|
}
|
|
346
|
-
return [4 /*yield*/, getAuthorizedQuery(entry, __assign({}, payload.query),
|
|
352
|
+
return [4 /*yield*/, getAuthorizedQuery(entry, __assign({}, payload.query), currentUser())];
|
|
347
353
|
case 1:
|
|
348
354
|
query = _a.sent();
|
|
349
355
|
if (!query) {
|
|
@@ -422,7 +428,9 @@ exports.installRealtimeSocketHandlers = installRealtimeSocketHandlers;
|
|
|
422
428
|
var RealtimeApp = /** @class */ (function () {
|
|
423
429
|
function RealtimeApp(config) {
|
|
424
430
|
if (config === void 0) { config = {}; }
|
|
431
|
+
this.app = null;
|
|
425
432
|
this.io = null;
|
|
433
|
+
this.sessionRevalidation = null;
|
|
426
434
|
this.config = config;
|
|
427
435
|
}
|
|
428
436
|
/**
|
|
@@ -430,6 +438,7 @@ var RealtimeApp = /** @class */ (function () {
|
|
|
430
438
|
*/
|
|
431
439
|
RealtimeApp.prototype.register = function (app) {
|
|
432
440
|
var _this = this;
|
|
441
|
+
this.app = app;
|
|
433
442
|
app.get("/realtime/health", function (_req, res) {
|
|
434
443
|
var _a, _b, _c, _d;
|
|
435
444
|
var connected = (_c = (_b = (_a = _this.io) === null || _a === void 0 ? void 0 : _a.engine) === null || _b === void 0 ? void 0 : _b.clientsCount) !== null && _c !== void 0 ? _c : 0;
|
|
@@ -445,7 +454,8 @@ var RealtimeApp = /** @class */ (function () {
|
|
|
445
454
|
* and starts the change stream watcher.
|
|
446
455
|
*/
|
|
447
456
|
RealtimeApp.prototype.onServerCreated = function (server) {
|
|
448
|
-
var
|
|
457
|
+
var _this = this;
|
|
458
|
+
var _a, _b, _c, _d, _e;
|
|
449
459
|
var debug = (_a = this.config.debug) !== null && _a !== void 0 ? _a : false;
|
|
450
460
|
var logInfo = function (message) {
|
|
451
461
|
if (debug) {
|
|
@@ -454,14 +464,17 @@ var RealtimeApp = /** @class */ (function () {
|
|
|
454
464
|
};
|
|
455
465
|
try {
|
|
456
466
|
logInfo("[realtime] Setting up Socket.io server...");
|
|
457
|
-
|
|
458
|
-
|
|
467
|
+
// Prefer an injected Server constructor in tests so callers never need
|
|
468
|
+
// process-wide `mock.module("socket.io")` (which poisons later files).
|
|
469
|
+
var SocketServerCtor = (_b = this.config.SocketServer) !== null && _b !== void 0 ? _b : socket_io_1.Server;
|
|
470
|
+
this.io = new SocketServerCtor(server, {
|
|
471
|
+
cors: (_c = this.config.cors) !== null && _c !== void 0 ? _c : {
|
|
459
472
|
methods: ["GET", "POST"],
|
|
460
473
|
origin: "*",
|
|
461
474
|
},
|
|
462
475
|
});
|
|
463
|
-
// JWT
|
|
464
|
-
var tokenSecret = (
|
|
476
|
+
// Authentication middleware: legacy JWT first, optionally Better Auth sessions.
|
|
477
|
+
var tokenSecret = (_d = this.config.tokenSecret) !== null && _d !== void 0 ? _d : process.env.TOKEN_SECRET;
|
|
465
478
|
if (!tokenSecret) {
|
|
466
479
|
throw new errors_1.APIError({
|
|
467
480
|
status: 500,
|
|
@@ -469,18 +482,42 @@ var RealtimeApp = /** @class */ (function () {
|
|
|
469
482
|
"Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
|
|
470
483
|
});
|
|
471
484
|
}
|
|
472
|
-
|
|
473
|
-
|
|
485
|
+
// D1: pass the issuer through for parity with the HTTP JWT path
|
|
486
|
+
// (jwt.verify(token, secret, {issuer})) — without it a validly-signed token
|
|
487
|
+
// issued for a different TOKEN_ISSUER was silently accepted over sockets. A
|
|
488
|
+
// thunk (not a value captured once here) so a later change to
|
|
489
|
+
// process.env.TOKEN_ISSUER — or to an explicitly configured tokenIssuer — is
|
|
490
|
+
// honored on every handshake, matching the HTTP path's per-request env read.
|
|
491
|
+
var resolveTokenIssuer = function () { var _a; return (_a = _this.config.tokenIssuer) !== null && _a !== void 0 ? _a : process.env.TOKEN_ISSUER; };
|
|
492
|
+
this.io.use((0, socketAuth_1.createSocketAuthMiddleware)({
|
|
493
|
+
betterAuth: this.config.betterAuth,
|
|
494
|
+
issuer: resolveTokenIssuer,
|
|
495
|
+
tokenSecret: tokenSecret,
|
|
474
496
|
}));
|
|
475
|
-
logInfo("[realtime]
|
|
497
|
+
logInfo("[realtime] Socket auth middleware added (JWT".concat(this.config.betterAuth ? " + Better Auth" : "", ")"));
|
|
498
|
+
// Task 9.21: tenant/custom sync scopes can only be resolved from the full user
|
|
499
|
+
// document, so warn loudly here (once, at startup) rather than silently serving
|
|
500
|
+
// empty tenant streams for the life of the process.
|
|
501
|
+
(0, registry_1.warnOnSyncScopesWithoutUserModel)({ userModel: this.config.userModel });
|
|
476
502
|
// Configure adapter for multi-instance deployments
|
|
477
503
|
this.setupAdapter(logInfo);
|
|
478
504
|
// Connection handling
|
|
479
505
|
this.io.on("connection", function (socket) {
|
|
506
|
+
var _a, _b;
|
|
480
507
|
try {
|
|
481
|
-
//
|
|
508
|
+
// D2: load the full user document once at handshake (by the decoded
|
|
509
|
+
// token's id) and cache it on socket.data.fullUser — getSocketUser prefers
|
|
510
|
+
// it over the synthetic {_id, admin, id} shape for every authorization
|
|
511
|
+
// check below. Fire-and-forget: handlers install synchronously and fall
|
|
512
|
+
// back to the synthetic shape until this resolves.
|
|
513
|
+
void (0, sessionRevalidation_1.loadFullUserForSocket)(socket, _this.config.userModel);
|
|
514
|
+
// The auth middleware adds `decodedToken` at runtime; cast through
|
|
482
515
|
// RealtimeSocketLike (a structural subset) to keep socket handler logic testable.
|
|
483
516
|
(0, exports.installRealtimeSocketHandlers)(socket, { logInfo: logInfo });
|
|
517
|
+
// Sync protocol handlers (sync:subscribe / sync:mutate). Options come from the
|
|
518
|
+
// SyncApp registered on this Express app or an explicit `sync` override here;
|
|
519
|
+
// with neither, the handlers still install and reject unknown collections.
|
|
520
|
+
(0, socketHandlers_1.installSyncSocketHandlers)(_this.io, socket, (_b = (_a = _this.config.sync) !== null && _a !== void 0 ? _a : (_this.app ? (0, syncApp_1.getSyncAppOptions)(_this.app) : undefined)) !== null && _b !== void 0 ? _b : {}, { logInfo: logInfo });
|
|
484
521
|
}
|
|
485
522
|
catch (error) {
|
|
486
523
|
logger_1.logger.error("[realtime] Error handling connection: ".concat(error));
|
|
@@ -491,8 +528,24 @@ var RealtimeApp = /** @class */ (function () {
|
|
|
491
528
|
logger_1.logger.error("[realtime] Connection error: ".concat(error.message));
|
|
492
529
|
Sentry.captureException(error);
|
|
493
530
|
});
|
|
494
|
-
// Start the change stream watcher
|
|
495
|
-
|
|
531
|
+
// Start the change stream watcher (injectable for unit tests — see SocketServer).
|
|
532
|
+
var startWatcher = (_e = this.config.startChangeStreamWatcher) !== null && _e !== void 0 ? _e : changeStreamWatcher_1.startChangeStreamWatcher;
|
|
533
|
+
startWatcher(this.io, this.config.changeStream, debug);
|
|
534
|
+
// D1: periodic session re-validation sweep — disconnects sockets whose JWT has
|
|
535
|
+
// expired, whose Better Auth session is no longer valid, or whose user has
|
|
536
|
+
// since been disabled; also refreshes socket.data.fullUser (D2) and
|
|
537
|
+
// re-resolves sync room membership (D4) for sockets that remain valid.
|
|
538
|
+
// A thunk (not a snapshot) reads this app's SyncApp options fresh on every sweep.
|
|
539
|
+
this.sessionRevalidation = (0, sessionRevalidation_1.startSessionRevalidationSweep)(this.io, function () {
|
|
540
|
+
var _a;
|
|
541
|
+
return ({
|
|
542
|
+
betterAuth: _this.config.betterAuth,
|
|
543
|
+
intervalMs: _this.config.sessionRevalidationIntervalMs,
|
|
544
|
+
logInfo: logInfo,
|
|
545
|
+
sync: (_a = _this.config.sync) !== null && _a !== void 0 ? _a : (_this.app ? (0, syncApp_1.getSyncAppOptions)(_this.app) : undefined),
|
|
546
|
+
userModel: _this.config.userModel,
|
|
547
|
+
});
|
|
548
|
+
});
|
|
496
549
|
logInfo("[realtime] Socket.io server setup complete");
|
|
497
550
|
}
|
|
498
551
|
catch (error) {
|
|
@@ -513,22 +566,25 @@ var RealtimeApp = /** @class */ (function () {
|
|
|
513
566
|
RealtimeApp.prototype.close = function () {
|
|
514
567
|
return __awaiter(this, void 0, void 0, function () {
|
|
515
568
|
var error_2;
|
|
516
|
-
|
|
517
|
-
|
|
569
|
+
var _a;
|
|
570
|
+
return __generator(this, function (_b) {
|
|
571
|
+
switch (_b.label) {
|
|
518
572
|
case 0:
|
|
519
|
-
|
|
573
|
+
_b.trys.push([0, 4, , 5]);
|
|
574
|
+
(_a = this.sessionRevalidation) === null || _a === void 0 ? void 0 : _a.stop();
|
|
575
|
+
this.sessionRevalidation = null;
|
|
520
576
|
return [4 /*yield*/, (0, changeStreamWatcher_1.stopChangeStreamWatcher)()];
|
|
521
577
|
case 1:
|
|
522
|
-
|
|
578
|
+
_b.sent();
|
|
523
579
|
if (!this.io) return [3 /*break*/, 3];
|
|
524
580
|
return [4 /*yield*/, this.io.close()];
|
|
525
581
|
case 2:
|
|
526
|
-
|
|
582
|
+
_b.sent();
|
|
527
583
|
this.io = null;
|
|
528
|
-
|
|
584
|
+
_b.label = 3;
|
|
529
585
|
case 3: return [3 /*break*/, 5];
|
|
530
586
|
case 4:
|
|
531
|
-
error_2 =
|
|
587
|
+
error_2 = _b.sent();
|
|
532
588
|
logger_1.logger.error("[realtime] Error closing: ".concat(error_2));
|
|
533
589
|
return [3 /*break*/, 5];
|
|
534
590
|
case 5: return [2 /*return*/];
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { Server, Socket } from "socket.io";
|
|
2
|
+
import type { UserModel } from "../auth";
|
|
3
|
+
import type { SyncAppOptions } from "../sync/routes";
|
|
4
|
+
import type { BetterAuthSocketOptions } from "./socketAuth";
|
|
5
|
+
import { type SocketDataBag, type SocketWithDecodedToken } from "./socketUser";
|
|
6
|
+
/**
|
|
7
|
+
* Default interval for the periodic socket session re-validation sweep (D1): 60
|
|
8
|
+
* seconds. Sockets authenticate once at handshake; without a sweep, a revoked
|
|
9
|
+
* session, an expired token, or a user subsequently disabled keeps streaming deltas
|
|
10
|
+
* (including PHI) indefinitely.
|
|
11
|
+
*/
|
|
12
|
+
export declare const DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = 60000;
|
|
13
|
+
/** Minimal socket shape the sweep needs. Lets tests drive it with a mock. */
|
|
14
|
+
export interface RevalidatableSocket extends SocketWithDecodedToken {
|
|
15
|
+
id: string;
|
|
16
|
+
encodedToken?: string;
|
|
17
|
+
data?: SocketDataBag;
|
|
18
|
+
emit: (event: string, payload?: unknown) => void;
|
|
19
|
+
disconnect: (close?: boolean) => void;
|
|
20
|
+
join: (room: string) => Promise<void> | void;
|
|
21
|
+
leave: (room: string) => Promise<void> | void;
|
|
22
|
+
}
|
|
23
|
+
export interface SessionRevalidationOptions {
|
|
24
|
+
/** Application user model, for reloading the full user and its `disabled` flag. */
|
|
25
|
+
userModel?: UserModel;
|
|
26
|
+
/** Enables re-validating Better Auth-authenticated sockets. */
|
|
27
|
+
betterAuth?: BetterAuthSocketOptions;
|
|
28
|
+
/** Active SyncAppOptions (for `getUserScopes`), used by D4's room re-resolution. */
|
|
29
|
+
sync?: SyncAppOptions;
|
|
30
|
+
logInfo?: (message: string) => void;
|
|
31
|
+
}
|
|
32
|
+
/** Result of re-validating a single socket, for tests/observability. */
|
|
33
|
+
export type RevalidationOutcome = "valid" | "expired" | "disabled" | "invalid-session";
|
|
34
|
+
/**
|
|
35
|
+
* Re-run the cheap parts of the auth validator for an already-connected socket:
|
|
36
|
+
* - JWT sockets (`decodedToken.authKind === "jwt"`): verify `exp` locally (no
|
|
37
|
+
* signature re-check — a stolen-but-still-valid token is not this sweep's job;
|
|
38
|
+
* revocation-by-expiry and disablement are).
|
|
39
|
+
* - Better Auth sockets (`decodedToken.authKind === "better-auth"`): re-run
|
|
40
|
+
* `auth.api.getSession` for the retained session token.
|
|
41
|
+
* Also reloads the user's `disabled` flag (and the full user document, refreshing
|
|
42
|
+
* `socket.data.fullUser` for D2) when a `userModel` is configured.
|
|
43
|
+
*/
|
|
44
|
+
export declare const revalidateSocketSession: (socket: RevalidatableSocket, options: SessionRevalidationOptions) => Promise<RevalidationOutcome>;
|
|
45
|
+
/**
|
|
46
|
+
* D4: re-resolve the streams the socket's user currently belongs to for every
|
|
47
|
+
* subscribed collection, and `socket.leave()` any previously-joined sync room the
|
|
48
|
+
* user no longer holds (e.g. a revoked organization membership). Joins any newly
|
|
49
|
+
* granted rooms too, mirroring what a fresh `sync:subscribe` would do, so a
|
|
50
|
+
* membership grant also takes effect without a reconnect.
|
|
51
|
+
*/
|
|
52
|
+
export declare const reresolveSyncRoomsForSocket: (socket: RevalidatableSocket, options: SessionRevalidationOptions) => Promise<void>;
|
|
53
|
+
/**
|
|
54
|
+
* Run one sweep pass over every connected socket: re-validate the session (D1),
|
|
55
|
+
* disconnecting (`sync:auth-expired` then `disconnect(true)`) any socket that fails,
|
|
56
|
+
* and re-resolve sync room membership (D4) for sockets that remain valid.
|
|
57
|
+
*/
|
|
58
|
+
export declare const runSessionRevalidationSweep: (io: Server, options?: SessionRevalidationOptions) => Promise<void>;
|
|
59
|
+
/** Handle returned by {@link startSessionRevalidationSweep}; call to stop the timer. */
|
|
60
|
+
export type SessionRevalidationHandle = {
|
|
61
|
+
stop: () => void;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* Start the periodic sweep (D1). Returns a handle to stop it (called from
|
|
65
|
+
* `RealtimeApp.close()`). A `intervalMs` of 0 disables the sweep (useful for tests
|
|
66
|
+
* that don't want a background timer).
|
|
67
|
+
*
|
|
68
|
+
* `options` may be a plain object or a thunk resolved fresh on EVERY tick — pass a
|
|
69
|
+
* thunk when any field (notably `sync`, whose `getUserScopes` resolver is published
|
|
70
|
+
* by the `SyncApp` plugin and may not be registered yet, or may change, at the time
|
|
71
|
+
* `RealtimeApp.onServerCreated()` runs) must never go stale for the lifetime of the
|
|
72
|
+
* sweep, mirroring the per-handshake freshness `createLegacyJwtValidator`'s issuer
|
|
73
|
+
* thunk already provides.
|
|
74
|
+
*/
|
|
75
|
+
export declare const startSessionRevalidationSweep: (io: Server, optionsOrThunk?: (SessionRevalidationOptions & {
|
|
76
|
+
intervalMs?: number;
|
|
77
|
+
}) | (() => SessionRevalidationOptions & {
|
|
78
|
+
intervalMs?: number;
|
|
79
|
+
})) => SessionRevalidationHandle;
|
|
80
|
+
/**
|
|
81
|
+
* Load the full user document for a just-authenticated socket and cache it on
|
|
82
|
+
* `socket.data.fullUser` (D2). Called once at handshake, right after the auth
|
|
83
|
+
* middleware succeeds; the periodic sweep (D1) refreshes it afterwards. A no-op when
|
|
84
|
+
* no `userModel` is configured (falls back to the synthetic decoded-token shape via
|
|
85
|
+
* `getSocketUser`) or the decoded token carries no id (should not happen for a
|
|
86
|
+
* socket that passed auth, but guarded defensively).
|
|
87
|
+
*/
|
|
88
|
+
export declare const loadFullUserForSocket: (socket: Socket & {
|
|
89
|
+
data: SocketDataBag;
|
|
90
|
+
}, userModel?: UserModel) => Promise<void>;
|