@terreno/api 0.31.0 → 56.0.0-beta.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.
Files changed (250) hide show
  1. package/CHANGELOG.md +122 -2
  2. package/LICENSE +202 -21
  3. package/dist/api.d.ts +12 -3
  4. package/dist/api.js +110 -361
  5. package/dist/auth.d.ts +26 -0
  6. package/dist/auth.js +100 -1
  7. package/dist/betterAuth.d.ts +5 -0
  8. package/dist/betterAuthSetup.d.ts +1 -15
  9. package/dist/betterAuthSetup.js +29 -8
  10. package/dist/configurationPlugin.js +2 -2
  11. package/dist/docLoader.js +12 -9
  12. package/dist/errors.d.ts +13 -0
  13. package/dist/errors.js +29 -1
  14. package/dist/expressServer.js +5 -11
  15. package/dist/githubAuth.js +4 -1
  16. package/dist/index.d.ts +17 -1
  17. package/dist/index.js +29 -1
  18. package/dist/middleware.d.ts +7 -0
  19. package/dist/middleware.js +16 -1
  20. package/dist/openApiCompat.d.ts +10 -1
  21. package/dist/openApiCompat.js +115 -47
  22. package/dist/permissions.d.ts +27 -0
  23. package/dist/permissions.js +42 -1
  24. package/dist/plugins.d.ts +15 -3
  25. package/dist/plugins.js +36 -6
  26. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  27. package/dist/realtime/changeStreamWatcher.js +542 -137
  28. package/dist/realtime/realtimeApp.d.ts +3 -1
  29. package/dist/realtime/realtimeApp.js +75 -27
  30. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  31. package/dist/realtime/sessionRevalidation.js +438 -0
  32. package/dist/realtime/socketAuth.d.ts +97 -0
  33. package/dist/realtime/socketAuth.js +272 -0
  34. package/dist/realtime/socketUser.d.ts +54 -0
  35. package/dist/realtime/socketUser.js +75 -5
  36. package/dist/realtime/types.d.ts +40 -0
  37. package/dist/secretProviders.d.ts +23 -0
  38. package/dist/secretProviders.js +9 -3
  39. package/dist/sync/executors.d.ts +198 -0
  40. package/dist/sync/executors.js +670 -0
  41. package/dist/sync/loadHarness.js +807 -0
  42. package/dist/sync/models.d.ts +216 -0
  43. package/dist/sync/models.js +644 -0
  44. package/dist/sync/mutationHandler.d.ts +97 -0
  45. package/dist/sync/mutationHandler.js +886 -0
  46. package/dist/sync/registry.d.ts +73 -0
  47. package/dist/sync/registry.js +223 -0
  48. package/dist/sync/routes.d.ts +62 -0
  49. package/dist/sync/routes.js +936 -0
  50. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  51. package/dist/sync/scripts/compactTombstones.js +270 -0
  52. package/dist/sync/serialize.d.ts +20 -0
  53. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  54. package/dist/sync/socketHandlers.d.ts +54 -0
  55. package/dist/sync/socketHandlers.js +470 -0
  56. package/dist/sync/streams.d.ts +85 -0
  57. package/dist/sync/streams.js +221 -0
  58. package/dist/sync/syncApp.d.ts +29 -0
  59. package/dist/sync/syncApp.js +44 -0
  60. package/dist/sync/syncBatch.d.ts +71 -0
  61. package/dist/sync/syncBatch.js +252 -0
  62. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  63. package/dist/sync/syncSeqPlugin.js +903 -0
  64. package/dist/sync/types.d.ts +254 -0
  65. package/dist/sync/types.js +9 -0
  66. package/dist/terrenoApp.js +90 -27
  67. package/dist/tests/models.d.ts +11 -27
  68. package/dist/tests/models.js +3 -5
  69. package/dist/tests/testHelper.d.ts +3 -9
  70. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  71. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  72. package/package.json +10 -8
  73. package/src/__tests__/openApiCompat.test.ts +20 -0
  74. package/src/actions.test.ts +12 -19
  75. package/src/actions.ts +2 -2
  76. package/src/api.coverage.test.ts +9 -7
  77. package/src/api.errorPaths.test.ts +1 -47
  78. package/src/api.test.ts +12 -0
  79. package/src/api.ts +98 -317
  80. package/src/auth.test.ts +128 -176
  81. package/src/auth.ts +109 -0
  82. package/src/betterAuth.ts +6 -0
  83. package/src/betterAuthSetup.test.ts +34 -0
  84. package/src/betterAuthSetup.ts +27 -8
  85. package/src/configurationPlugin.ts +2 -2
  86. package/src/consentApp.test.ts +12 -12
  87. package/src/docLoader.ts +3 -1
  88. package/src/errors.ts +33 -0
  89. package/src/expressServer.test.ts +7 -1
  90. package/src/expressServer.ts +5 -11
  91. package/src/githubAuth.ts +3 -1
  92. package/src/index.ts +42 -0
  93. package/src/middleware.test.ts +40 -1
  94. package/src/middleware.ts +15 -0
  95. package/src/models/versionConfig.ts +1 -1
  96. package/src/openApiBuilder.test.ts +9 -24
  97. package/src/openApiCompat.ts +99 -45
  98. package/src/openApiValidator.test.ts +0 -41
  99. package/src/permissions.test.ts +75 -1
  100. package/src/permissions.ts +49 -0
  101. package/src/plugins.test.ts +54 -14
  102. package/src/plugins.ts +47 -9
  103. package/src/populate.test.ts +16 -25
  104. package/src/realtime/changeStreamWatcher.ts +552 -114
  105. package/src/realtime/realtime.test.ts +157 -239
  106. package/src/realtime/realtimeApp.ts +80 -19
  107. package/src/realtime/sessionRevalidation.test.ts +423 -0
  108. package/src/realtime/sessionRevalidation.ts +273 -0
  109. package/src/realtime/socketAuth.test.ts +355 -0
  110. package/src/realtime/socketAuth.ts +228 -0
  111. package/src/realtime/socketUser.ts +69 -0
  112. package/src/realtime/types.ts +40 -0
  113. package/src/secretProviders.test.ts +7 -1
  114. package/src/secretProviders.ts +15 -3
  115. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  116. package/src/sync/executors.test.ts +882 -0
  117. package/src/sync/executors.ts +703 -0
  118. package/src/sync/integration.test.ts +1160 -0
  119. package/src/sync/loadHarness.ts +618 -0
  120. package/src/sync/models.ts +640 -0
  121. package/src/sync/mutationHandler.test.ts +1252 -0
  122. package/src/sync/mutationHandler.ts +850 -0
  123. package/src/sync/registry.ts +232 -0
  124. package/src/sync/routes.ts +812 -0
  125. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  126. package/src/sync/scripts/compactTombstones.ts +145 -0
  127. package/src/sync/serialize.ts +48 -0
  128. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  129. package/src/sync/socketHandlers.ts +320 -0
  130. package/src/sync/streams.ts +188 -0
  131. package/src/sync/sync.test.ts +582 -0
  132. package/src/sync/syncApp.ts +44 -0
  133. package/src/sync/syncBatch.ts +219 -0
  134. package/src/sync/syncFrontier.test.ts +494 -0
  135. package/src/sync/syncPhaseC.test.ts +718 -0
  136. package/src/sync/syncRoutes.test.ts +865 -0
  137. package/src/sync/syncSeqPlugin.ts +738 -0
  138. package/src/sync/syncSocket.test.ts +1440 -0
  139. package/src/sync/types.ts +270 -0
  140. package/src/terrenoApp.ts +37 -17
  141. package/src/tests/bunSetup.ts +8 -0
  142. package/src/tests/models.ts +6 -8
  143. package/tsconfig.json +4 -4
  144. package/tsconfig.typedoc.json +7 -1
  145. package/dist/__tests__/openApiCompat.test.js +0 -317
  146. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  147. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  148. package/dist/actions.openApi.test.d.ts +0 -1
  149. package/dist/actions.openApi.test.js +0 -253
  150. package/dist/actions.test.d.ts +0 -1
  151. package/dist/actions.test.js +0 -1087
  152. package/dist/api.arrayOperations.test.d.ts +0 -1
  153. package/dist/api.arrayOperations.test.js +0 -878
  154. package/dist/api.asyncHandler.test.d.ts +0 -1
  155. package/dist/api.asyncHandler.test.js +0 -236
  156. package/dist/api.coverage.test.d.ts +0 -1
  157. package/dist/api.coverage.test.js +0 -192
  158. package/dist/api.errorPaths.test.d.ts +0 -1
  159. package/dist/api.errorPaths.test.js +0 -887
  160. package/dist/api.errors.test.d.ts +0 -1
  161. package/dist/api.errors.test.js +0 -185
  162. package/dist/api.hooks.test.d.ts +0 -1
  163. package/dist/api.hooks.test.js +0 -950
  164. package/dist/api.query.test.d.ts +0 -1
  165. package/dist/api.query.test.js +0 -948
  166. package/dist/api.test.d.ts +0 -1
  167. package/dist/api.test.js +0 -2820
  168. package/dist/auth.compile.test.d.ts +0 -1
  169. package/dist/auth.compile.test.js +0 -201
  170. package/dist/auth.coverage.test.d.ts +0 -1
  171. package/dist/auth.coverage.test.js +0 -202
  172. package/dist/auth.test.d.ts +0 -1
  173. package/dist/auth.test.js +0 -2286
  174. package/dist/betterAuth.test.d.ts +0 -1
  175. package/dist/betterAuth.test.js +0 -181
  176. package/dist/betterAuthApp.test.d.ts +0 -1
  177. package/dist/betterAuthApp.test.js +0 -242
  178. package/dist/betterAuthSetup.test.d.ts +0 -1
  179. package/dist/betterAuthSetup.test.js +0 -762
  180. package/dist/config.test.d.ts +0 -1
  181. package/dist/config.test.js +0 -353
  182. package/dist/configuration.test.d.ts +0 -1
  183. package/dist/configuration.test.js +0 -980
  184. package/dist/configurationPlugin.test.d.ts +0 -1
  185. package/dist/configurationPlugin.test.js +0 -827
  186. package/dist/consentApp.test.d.ts +0 -1
  187. package/dist/consentApp.test.js +0 -1411
  188. package/dist/docLoader.test.d.ts +0 -1
  189. package/dist/docLoader.test.js +0 -137
  190. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  191. package/dist/envConfigurationPlugin.test.js +0 -369
  192. package/dist/errors.test.d.ts +0 -1
  193. package/dist/errors.test.js +0 -607
  194. package/dist/expressServer.test.d.ts +0 -1
  195. package/dist/expressServer.test.js +0 -1249
  196. package/dist/githubAuth.test.d.ts +0 -1
  197. package/dist/githubAuth.test.js +0 -1142
  198. package/dist/httpClient.test.d.ts +0 -1
  199. package/dist/httpClient.test.js +0 -1471
  200. package/dist/logger.test.d.ts +0 -1
  201. package/dist/logger.test.js +0 -685
  202. package/dist/middleware.test.d.ts +0 -1
  203. package/dist/middleware.test.js +0 -241
  204. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  205. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  206. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  207. package/dist/notifiers/slackNotifier.test.js +0 -297
  208. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  209. package/dist/notifiers/zoomNotifier.test.js +0 -373
  210. package/dist/openApi.test.d.ts +0 -1
  211. package/dist/openApi.test.js +0 -620
  212. package/dist/openApiBuilder.test.d.ts +0 -1
  213. package/dist/openApiBuilder.test.js +0 -599
  214. package/dist/openApiEtag.test.d.ts +0 -1
  215. package/dist/openApiEtag.test.js +0 -86
  216. package/dist/openApiValidator.test.d.ts +0 -1
  217. package/dist/openApiValidator.test.js +0 -795
  218. package/dist/permissions.middleware.test.d.ts +0 -1
  219. package/dist/permissions.middleware.test.js +0 -308
  220. package/dist/permissions.test.d.ts +0 -1
  221. package/dist/permissions.test.js +0 -439
  222. package/dist/plugins.test.d.ts +0 -1
  223. package/dist/plugins.test.js +0 -902
  224. package/dist/populate.test.d.ts +0 -1
  225. package/dist/populate.test.js +0 -370
  226. package/dist/realtime/realtime.test.d.ts +0 -10
  227. package/dist/realtime/realtime.test.js +0 -4213
  228. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  229. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  230. package/dist/requestContext.test.d.ts +0 -1
  231. package/dist/requestContext.test.js +0 -412
  232. package/dist/scriptRunner.test.d.ts +0 -1
  233. package/dist/scriptRunner.test.js +0 -386
  234. package/dist/secretProviders.test.d.ts +0 -1
  235. package/dist/secretProviders.test.js +0 -726
  236. package/dist/syncConsents.test.d.ts +0 -1
  237. package/dist/syncConsents.test.js +0 -522
  238. package/dist/terrenoApp.test.d.ts +0 -1
  239. package/dist/terrenoApp.test.js +0 -489
  240. package/dist/tests/bunSetup.d.ts +0 -1
  241. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  242. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  243. package/dist/tests/testEnv.d.ts +0 -0
  244. package/dist/tests/testEnv.js +0 -6
  245. package/dist/transformers.test.d.ts +0 -1
  246. package/dist/transformers.test.js +0 -423
  247. package/dist/utils.test.d.ts +0 -1
  248. package/dist/utils.test.js +0 -242
  249. package/src/realtime/realtimeAppSetup.test.ts +0 -161
  250. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -28,7 +28,7 @@ export interface RealtimeSocketLike extends SocketWithDecodedToken {
28
28
  join: (room: string) => Promise<void> | void;
29
29
  leave: (room: string) => Promise<void> | void;
30
30
  emit: (event: string, payload: unknown) => void;
31
- on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
31
+ on: (event: string, handler: (...args: any[]) => any) => void;
32
32
  }
33
33
  /**
34
34
  * Install the realtime subscription handlers on a single socket. Extracted from the
@@ -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,17 @@ 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
- var errors_1 = require("../errors");
88
86
  var logger_1 = require("../logger");
89
87
  var permissions_1 = require("../permissions");
88
+ var registry_1 = require("../sync/registry");
89
+ var socketHandlers_1 = require("../sync/socketHandlers");
90
+ var syncApp_1 = require("../sync/syncApp");
90
91
  var changeStreamWatcher_1 = require("./changeStreamWatcher");
91
92
  var queryStore_1 = require("./queryStore");
92
- var registry_1 = require("./registry");
93
+ var registry_2 = require("./registry");
94
+ var sessionRevalidation_1 = require("./sessionRevalidation");
95
+ var socketAuth_1 = require("./socketAuth");
93
96
  var socketUser_1 = require("./socketUser");
94
97
  /**
95
98
  * Caps on per-socket subscriptions. Prevents a malicious or buggy client from
@@ -178,7 +181,9 @@ var installRealtimeSocketHandlers = function (socket, options) {
178
181
  var logInfo = (_a = options.logInfo) !== null && _a !== void 0 ? _a : (function () { });
179
182
  var userId = (_b = socket.decodedToken) === null || _b === void 0 ? void 0 : _b.id;
180
183
  var isAdmin = ((_c = socket.decodedToken) === null || _c === void 0 ? void 0 : _c.admin) === true;
181
- var user = (0, socketUser_1.getSocketUser)(socket);
184
+ // D2: re-derive per event rather than capturing once at install time, so a
185
+ // handshake-time-loaded full user (or one refreshed by D1's sweep) is always used.
186
+ var currentUser = function () { return (0, socketUser_1.getSocketUser)(socket); };
182
187
  var counts = { document: 0, model: 0, query: 0 };
183
188
  var joinUserRooms = function () { return __awaiter(void 0, void 0, void 0, function () {
184
189
  return __generator(this, function (_a) {
@@ -218,7 +223,7 @@ var installRealtimeSocketHandlers = function (socket, options) {
218
223
  logInfo("[realtime] User ".concat(userId, " hit model subscription limit"));
219
224
  return [2 /*return*/];
220
225
  }
221
- entry = (0, registry_1.findRegistryEntryByRoutePath)(modelName);
226
+ entry = (0, registry_2.findRegistryEntryByRoutePath)(modelName);
222
227
  if (!entry) {
223
228
  logInfo("[realtime] User ".concat(userId, " denied model subscription: collection \"").concat(modelName, "\" not registered"));
224
229
  return [2 /*return*/];
@@ -231,7 +236,7 @@ var installRealtimeSocketHandlers = function (socket, options) {
231
236
  "owner strategy restricts model room to admins");
232
237
  return [2 /*return*/];
233
238
  }
234
- return [4 /*yield*/, canSubscribe(entry, "list", user)];
239
+ return [4 /*yield*/, canSubscribe(entry, "list", currentUser())];
235
240
  case 1:
236
241
  if (!(_a.sent())) {
237
242
  logInfo("[realtime] User ".concat(userId, " denied model subscription for ").concat(modelName, ": list permission denied"));
@@ -276,13 +281,13 @@ var installRealtimeSocketHandlers = function (socket, options) {
276
281
  logInfo("[realtime] User ".concat(userId, " hit document subscription limit"));
277
282
  return [2 /*return*/];
278
283
  }
279
- entry = (0, registry_1.findRegistryEntryByRoutePath)(payload.collection);
284
+ entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
280
285
  if (!entry) {
281
286
  logInfo("[realtime] User ".concat(userId, " denied document subscription: ") +
282
287
  "collection \"".concat(payload.collection, "\" not registered"));
283
288
  return [2 /*return*/];
284
289
  }
285
- return [4 /*yield*/, canSubscribe(entry, "read", user)];
290
+ return [4 /*yield*/, canSubscribe(entry, "read", currentUser())];
286
291
  case 1:
287
292
  if (!(_a.sent())) {
288
293
  logInfo("[realtime] User ".concat(userId, " denied document subscription for ") +
@@ -337,13 +342,13 @@ var installRealtimeSocketHandlers = function (socket, options) {
337
342
  logInfo("[realtime] User ".concat(userId, " hit query subscription limit"));
338
343
  return [2 /*return*/];
339
344
  }
340
- entry = (0, registry_1.findRegistryEntryByRoutePath)(payload.collection);
345
+ entry = (0, registry_2.findRegistryEntryByRoutePath)(payload.collection);
341
346
  if (!entry) {
342
347
  logInfo("[realtime] User ".concat(userId, " denied query subscription: ") +
343
348
  "collection \"".concat(payload.collection, "\" not registered"));
344
349
  return [2 /*return*/];
345
350
  }
346
- return [4 /*yield*/, getAuthorizedQuery(entry, __assign({}, payload.query), user)];
351
+ return [4 /*yield*/, getAuthorizedQuery(entry, __assign({}, payload.query), currentUser())];
347
352
  case 1:
348
353
  query = _a.sent();
349
354
  if (!query) {
@@ -422,7 +427,9 @@ exports.installRealtimeSocketHandlers = installRealtimeSocketHandlers;
422
427
  var RealtimeApp = /** @class */ (function () {
423
428
  function RealtimeApp(config) {
424
429
  if (config === void 0) { config = {}; }
430
+ this.app = null;
425
431
  this.io = null;
432
+ this.sessionRevalidation = null;
426
433
  this.config = config;
427
434
  }
428
435
  /**
@@ -430,6 +437,7 @@ var RealtimeApp = /** @class */ (function () {
430
437
  */
431
438
  RealtimeApp.prototype.register = function (app) {
432
439
  var _this = this;
440
+ this.app = app;
433
441
  app.get("/realtime/health", function (_req, res) {
434
442
  var _a, _b, _c, _d;
435
443
  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,6 +453,7 @@ var RealtimeApp = /** @class */ (function () {
445
453
  * and starts the change stream watcher.
446
454
  */
447
455
  RealtimeApp.prototype.onServerCreated = function (server) {
456
+ var _this = this;
448
457
  var _a, _b, _c;
449
458
  var debug = (_a = this.config.debug) !== null && _a !== void 0 ? _a : false;
450
459
  var logInfo = function (message) {
@@ -460,27 +469,48 @@ var RealtimeApp = /** @class */ (function () {
460
469
  origin: "*",
461
470
  },
462
471
  });
463
- // JWT authentication middleware
472
+ // Authentication middleware: legacy JWT first, optionally Better Auth sessions.
464
473
  var tokenSecret = (_c = this.config.tokenSecret) !== null && _c !== void 0 ? _c : process.env.TOKEN_SECRET;
465
474
  if (!tokenSecret) {
466
- throw new errors_1.APIError({
467
- status: 500,
468
- title: "[realtime] TOKEN_SECRET is required for socket authentication. " +
469
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
470
- });
475
+ throw new Error("[realtime] TOKEN_SECRET is required for socket authentication. " +
476
+ "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.");
471
477
  }
472
- this.io.use((0, socketio_jwt_1.authorize)({
473
- secret: tokenSecret,
478
+ // D1: pass the issuer through for parity with the HTTP JWT path
479
+ // (jwt.verify(token, secret, {issuer})) — without it a validly-signed token
480
+ // issued for a different TOKEN_ISSUER was silently accepted over sockets. A
481
+ // thunk (not a value captured once here) so a later change to
482
+ // process.env.TOKEN_ISSUER — or to an explicitly configured tokenIssuer — is
483
+ // honored on every handshake, matching the HTTP path's per-request env read.
484
+ var resolveTokenIssuer = function () { var _a; return (_a = _this.config.tokenIssuer) !== null && _a !== void 0 ? _a : process.env.TOKEN_ISSUER; };
485
+ this.io.use((0, socketAuth_1.createSocketAuthMiddleware)({
486
+ betterAuth: this.config.betterAuth,
487
+ issuer: resolveTokenIssuer,
488
+ tokenSecret: tokenSecret,
474
489
  }));
475
- logInfo("[realtime] JWT authorization middleware added");
490
+ logInfo("[realtime] Socket auth middleware added (JWT".concat(this.config.betterAuth ? " + Better Auth" : "", ")"));
491
+ // Task 9.21: tenant/custom sync scopes can only be resolved from the full user
492
+ // document, so warn loudly here (once, at startup) rather than silently serving
493
+ // empty tenant streams for the life of the process.
494
+ (0, registry_1.warnOnSyncScopesWithoutUserModel)({ userModel: this.config.userModel });
476
495
  // Configure adapter for multi-instance deployments
477
496
  this.setupAdapter(logInfo);
478
497
  // Connection handling
479
498
  this.io.on("connection", function (socket) {
499
+ var _a, _b;
480
500
  try {
481
- // socketio-jwt's authorize middleware adds `decodedToken` at runtime; cast through
501
+ // D2: load the full user document once at handshake (by the decoded
502
+ // token's id) and cache it on socket.data.fullUser — getSocketUser prefers
503
+ // it over the synthetic {_id, admin, id} shape for every authorization
504
+ // check below. Fire-and-forget: handlers install synchronously and fall
505
+ // back to the synthetic shape until this resolves.
506
+ void (0, sessionRevalidation_1.loadFullUserForSocket)(socket, _this.config.userModel);
507
+ // The auth middleware adds `decodedToken` at runtime; cast through
482
508
  // RealtimeSocketLike (a structural subset) to keep socket handler logic testable.
483
509
  (0, exports.installRealtimeSocketHandlers)(socket, { logInfo: logInfo });
510
+ // Sync protocol handlers (sync:subscribe / sync:mutate). Options come from the
511
+ // SyncApp registered on this Express app or an explicit `sync` override here;
512
+ // with neither, the handlers still install and reject unknown collections.
513
+ (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
514
  }
485
515
  catch (error) {
486
516
  logger_1.logger.error("[realtime] Error handling connection: ".concat(error));
@@ -493,6 +523,21 @@ var RealtimeApp = /** @class */ (function () {
493
523
  });
494
524
  // Start the change stream watcher
495
525
  (0, changeStreamWatcher_1.startChangeStreamWatcher)(this.io, this.config.changeStream, debug);
526
+ // D1: periodic session re-validation sweep — disconnects sockets whose JWT has
527
+ // expired, whose Better Auth session is no longer valid, or whose user has
528
+ // since been disabled; also refreshes socket.data.fullUser (D2) and
529
+ // re-resolves sync room membership (D4) for sockets that remain valid.
530
+ // A thunk (not a snapshot) reads this app's SyncApp options fresh on every sweep.
531
+ this.sessionRevalidation = (0, sessionRevalidation_1.startSessionRevalidationSweep)(this.io, function () {
532
+ var _a;
533
+ return ({
534
+ betterAuth: _this.config.betterAuth,
535
+ intervalMs: _this.config.sessionRevalidationIntervalMs,
536
+ logInfo: logInfo,
537
+ sync: (_a = _this.config.sync) !== null && _a !== void 0 ? _a : (_this.app ? (0, syncApp_1.getSyncAppOptions)(_this.app) : undefined),
538
+ userModel: _this.config.userModel,
539
+ });
540
+ });
496
541
  logInfo("[realtime] Socket.io server setup complete");
497
542
  }
498
543
  catch (error) {
@@ -513,22 +558,25 @@ var RealtimeApp = /** @class */ (function () {
513
558
  RealtimeApp.prototype.close = function () {
514
559
  return __awaiter(this, void 0, void 0, function () {
515
560
  var error_2;
516
- return __generator(this, function (_a) {
517
- switch (_a.label) {
561
+ var _a;
562
+ return __generator(this, function (_b) {
563
+ switch (_b.label) {
518
564
  case 0:
519
- _a.trys.push([0, 4, , 5]);
565
+ _b.trys.push([0, 4, , 5]);
566
+ (_a = this.sessionRevalidation) === null || _a === void 0 ? void 0 : _a.stop();
567
+ this.sessionRevalidation = null;
520
568
  return [4 /*yield*/, (0, changeStreamWatcher_1.stopChangeStreamWatcher)()];
521
569
  case 1:
522
- _a.sent();
570
+ _b.sent();
523
571
  if (!this.io) return [3 /*break*/, 3];
524
572
  return [4 /*yield*/, this.io.close()];
525
573
  case 2:
526
- _a.sent();
574
+ _b.sent();
527
575
  this.io = null;
528
- _a.label = 3;
576
+ _b.label = 3;
529
577
  case 3: return [3 /*break*/, 5];
530
578
  case 4:
531
- error_2 = _a.sent();
579
+ error_2 = _b.sent();
532
580
  logger_1.logger.error("[realtime] Error closing: ".concat(error_2));
533
581
  return [3 /*break*/, 5];
534
582
  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>;