@terreno/api 0.30.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 (226) hide show
  1. package/dist/api.d.ts +10 -0
  2. package/dist/api.js +110 -361
  3. package/dist/auth.d.ts +26 -0
  4. package/dist/auth.js +100 -1
  5. package/dist/betterAuth.d.ts +5 -0
  6. package/dist/betterAuthSetup.js +23 -4
  7. package/dist/docLoader.js +12 -9
  8. package/dist/errors.d.ts +13 -0
  9. package/dist/errors.js +29 -1
  10. package/dist/index.d.ts +17 -1
  11. package/dist/index.js +29 -1
  12. package/dist/middleware.d.ts +7 -0
  13. package/dist/middleware.js +16 -1
  14. package/dist/openApiCompat.d.ts +10 -1
  15. package/dist/openApiCompat.js +115 -47
  16. package/dist/permissions.d.ts +27 -0
  17. package/dist/permissions.js +42 -1
  18. package/dist/plugins.d.ts +13 -0
  19. package/dist/plugins.js +35 -1
  20. package/dist/realtime/changeStreamWatcher.d.ts +100 -3
  21. package/dist/realtime/changeStreamWatcher.js +542 -137
  22. package/dist/realtime/realtimeApp.d.ts +2 -0
  23. package/dist/realtime/realtimeApp.js +73 -21
  24. package/dist/realtime/sessionRevalidation.d.ts +90 -0
  25. package/dist/realtime/sessionRevalidation.js +438 -0
  26. package/dist/realtime/socketAuth.d.ts +97 -0
  27. package/dist/realtime/socketAuth.js +272 -0
  28. package/dist/realtime/socketUser.d.ts +54 -0
  29. package/dist/realtime/socketUser.js +75 -5
  30. package/dist/realtime/types.d.ts +40 -0
  31. package/dist/secretProviders.d.ts +23 -0
  32. package/dist/secretProviders.js +9 -3
  33. package/dist/sync/executors.d.ts +198 -0
  34. package/dist/sync/executors.js +670 -0
  35. package/dist/sync/loadHarness.js +807 -0
  36. package/dist/sync/models.d.ts +216 -0
  37. package/dist/sync/models.js +644 -0
  38. package/dist/sync/mutationHandler.d.ts +97 -0
  39. package/dist/sync/mutationHandler.js +886 -0
  40. package/dist/sync/registry.d.ts +73 -0
  41. package/dist/sync/registry.js +223 -0
  42. package/dist/sync/routes.d.ts +62 -0
  43. package/dist/sync/routes.js +936 -0
  44. package/dist/sync/scripts/compactTombstones.d.ts +47 -0
  45. package/dist/sync/scripts/compactTombstones.js +270 -0
  46. package/dist/sync/serialize.d.ts +20 -0
  47. package/dist/{tests/bunSetup.js → sync/serialize.js} +35 -68
  48. package/dist/sync/socketHandlers.d.ts +54 -0
  49. package/dist/sync/socketHandlers.js +470 -0
  50. package/dist/sync/streams.d.ts +85 -0
  51. package/dist/sync/streams.js +221 -0
  52. package/dist/sync/syncApp.d.ts +29 -0
  53. package/dist/sync/syncApp.js +44 -0
  54. package/dist/sync/syncBatch.d.ts +71 -0
  55. package/dist/sync/syncBatch.js +252 -0
  56. package/dist/sync/syncSeqPlugin.d.ts +8 -0
  57. package/dist/sync/syncSeqPlugin.js +903 -0
  58. package/dist/sync/types.d.ts +254 -0
  59. package/dist/sync/types.js +9 -0
  60. package/dist/terrenoApp.js +90 -27
  61. package/dist/vendor/wesleytodd-openapi/index.d.ts +1 -1
  62. package/dist/vendor/wesleytodd-openapi/lib/ui.d.ts +2 -1
  63. package/package.json +7 -6
  64. package/src/__tests__/openApiCompat.test.ts +20 -0
  65. package/src/actions.openApi.test.ts +7 -10
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -295
  68. package/src/auth.test.ts +128 -176
  69. package/src/auth.ts +109 -0
  70. package/src/betterAuth.ts +6 -0
  71. package/src/betterAuthSetup.test.ts +34 -0
  72. package/src/betterAuthSetup.ts +20 -1
  73. package/src/docLoader.ts +3 -1
  74. package/src/errors.ts +33 -0
  75. package/src/expressServer.test.ts +7 -1
  76. package/src/index.ts +42 -0
  77. package/src/middleware.test.ts +40 -1
  78. package/src/middleware.ts +15 -0
  79. package/src/openApiCompat.ts +99 -45
  80. package/src/permissions.test.ts +75 -1
  81. package/src/permissions.ts +49 -0
  82. package/src/plugins.test.ts +54 -0
  83. package/src/plugins.ts +43 -0
  84. package/src/realtime/changeStreamWatcher.ts +552 -114
  85. package/src/realtime/realtime.test.ts +157 -0
  86. package/src/realtime/realtimeApp.ts +75 -11
  87. package/src/realtime/sessionRevalidation.test.ts +423 -0
  88. package/src/realtime/sessionRevalidation.ts +273 -0
  89. package/src/realtime/socketAuth.test.ts +355 -0
  90. package/src/realtime/socketAuth.ts +228 -0
  91. package/src/realtime/socketUser.ts +69 -0
  92. package/src/realtime/types.ts +40 -0
  93. package/src/secretProviders.test.ts +7 -1
  94. package/src/secretProviders.ts +15 -3
  95. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  96. package/src/sync/executors.test.ts +882 -0
  97. package/src/sync/executors.ts +703 -0
  98. package/src/sync/integration.test.ts +1160 -0
  99. package/src/sync/loadHarness.ts +618 -0
  100. package/src/sync/models.ts +640 -0
  101. package/src/sync/mutationHandler.test.ts +1252 -0
  102. package/src/sync/mutationHandler.ts +850 -0
  103. package/src/sync/registry.ts +232 -0
  104. package/src/sync/routes.ts +812 -0
  105. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  106. package/src/sync/scripts/compactTombstones.ts +145 -0
  107. package/src/sync/serialize.ts +48 -0
  108. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  109. package/src/sync/socketHandlers.ts +320 -0
  110. package/src/sync/streams.ts +188 -0
  111. package/src/sync/sync.test.ts +582 -0
  112. package/src/sync/syncApp.ts +44 -0
  113. package/src/sync/syncBatch.ts +219 -0
  114. package/src/sync/syncFrontier.test.ts +494 -0
  115. package/src/sync/syncPhaseC.test.ts +718 -0
  116. package/src/sync/syncRoutes.test.ts +865 -0
  117. package/src/sync/syncSeqPlugin.ts +738 -0
  118. package/src/sync/syncSocket.test.ts +1440 -0
  119. package/src/sync/types.ts +270 -0
  120. package/src/terrenoApp.ts +37 -17
  121. package/src/tests/bunSetup.ts +8 -0
  122. package/tsconfig.json +4 -4
  123. package/tsconfig.typedoc.json +7 -1
  124. package/dist/__tests__/openApiCompat.test.js +0 -317
  125. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  126. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  127. package/dist/actions.openApi.test.d.ts +0 -1
  128. package/dist/actions.openApi.test.js +0 -255
  129. package/dist/actions.test.d.ts +0 -1
  130. package/dist/actions.test.js +0 -1089
  131. package/dist/api.arrayOperations.test.d.ts +0 -1
  132. package/dist/api.arrayOperations.test.js +0 -878
  133. package/dist/api.asyncHandler.test.d.ts +0 -1
  134. package/dist/api.asyncHandler.test.js +0 -236
  135. package/dist/api.coverage.test.d.ts +0 -1
  136. package/dist/api.coverage.test.js +0 -194
  137. package/dist/api.errorPaths.test.d.ts +0 -1
  138. package/dist/api.errorPaths.test.js +0 -801
  139. package/dist/api.errors.test.d.ts +0 -1
  140. package/dist/api.errors.test.js +0 -185
  141. package/dist/api.hooks.test.d.ts +0 -1
  142. package/dist/api.hooks.test.js +0 -950
  143. package/dist/api.query.test.d.ts +0 -1
  144. package/dist/api.query.test.js +0 -948
  145. package/dist/api.test.d.ts +0 -1
  146. package/dist/api.test.js +0 -2820
  147. package/dist/auth.compile.test.d.ts +0 -1
  148. package/dist/auth.compile.test.js +0 -201
  149. package/dist/auth.coverage.test.d.ts +0 -1
  150. package/dist/auth.coverage.test.js +0 -202
  151. package/dist/auth.test.d.ts +0 -1
  152. package/dist/auth.test.js +0 -2286
  153. package/dist/betterAuth.test.d.ts +0 -1
  154. package/dist/betterAuth.test.js +0 -181
  155. package/dist/betterAuthApp.test.d.ts +0 -1
  156. package/dist/betterAuthApp.test.js +0 -242
  157. package/dist/betterAuthSetup.test.d.ts +0 -1
  158. package/dist/betterAuthSetup.test.js +0 -762
  159. package/dist/config.test.d.ts +0 -1
  160. package/dist/config.test.js +0 -353
  161. package/dist/configuration.test.d.ts +0 -1
  162. package/dist/configuration.test.js +0 -980
  163. package/dist/configurationPlugin.test.d.ts +0 -1
  164. package/dist/configurationPlugin.test.js +0 -827
  165. package/dist/consentApp.test.d.ts +0 -1
  166. package/dist/consentApp.test.js +0 -1415
  167. package/dist/docLoader.test.d.ts +0 -1
  168. package/dist/docLoader.test.js +0 -137
  169. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  170. package/dist/envConfigurationPlugin.test.js +0 -369
  171. package/dist/errors.test.d.ts +0 -1
  172. package/dist/errors.test.js +0 -607
  173. package/dist/expressServer.test.d.ts +0 -1
  174. package/dist/expressServer.test.js +0 -1249
  175. package/dist/githubAuth.test.d.ts +0 -1
  176. package/dist/githubAuth.test.js +0 -1142
  177. package/dist/httpClient.test.d.ts +0 -1
  178. package/dist/httpClient.test.js +0 -1471
  179. package/dist/logger.test.d.ts +0 -1
  180. package/dist/logger.test.js +0 -685
  181. package/dist/middleware.test.d.ts +0 -1
  182. package/dist/middleware.test.js +0 -241
  183. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  184. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  185. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  186. package/dist/notifiers/slackNotifier.test.js +0 -297
  187. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/zoomNotifier.test.js +0 -373
  189. package/dist/openApi.test.d.ts +0 -1
  190. package/dist/openApi.test.js +0 -620
  191. package/dist/openApiBuilder.test.d.ts +0 -1
  192. package/dist/openApiBuilder.test.js +0 -601
  193. package/dist/openApiEtag.test.d.ts +0 -1
  194. package/dist/openApiEtag.test.js +0 -86
  195. package/dist/openApiValidator.test.d.ts +0 -1
  196. package/dist/openApiValidator.test.js +0 -761
  197. package/dist/permissions.middleware.test.d.ts +0 -1
  198. package/dist/permissions.middleware.test.js +0 -308
  199. package/dist/permissions.test.d.ts +0 -1
  200. package/dist/permissions.test.js +0 -439
  201. package/dist/plugins.test.d.ts +0 -1
  202. package/dist/plugins.test.js +0 -890
  203. package/dist/populate.test.d.ts +0 -1
  204. package/dist/populate.test.js +0 -373
  205. package/dist/realtime/realtime.test.d.ts +0 -10
  206. package/dist/realtime/realtime.test.js +0 -3982
  207. package/dist/requestContext.test.d.ts +0 -1
  208. package/dist/requestContext.test.js +0 -412
  209. package/dist/scriptRunner.test.d.ts +0 -1
  210. package/dist/scriptRunner.test.js +0 -386
  211. package/dist/secretProviders.test.d.ts +0 -1
  212. package/dist/secretProviders.test.js +0 -726
  213. package/dist/syncConsents.test.d.ts +0 -1
  214. package/dist/syncConsents.test.js +0 -522
  215. package/dist/terrenoApp.test.d.ts +0 -1
  216. package/dist/terrenoApp.test.js +0 -489
  217. package/dist/tests/bunSetup.d.ts +0 -1
  218. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  219. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  220. package/dist/tests/testEnv.d.ts +0 -0
  221. package/dist/tests/testEnv.js +0 -6
  222. package/dist/transformers.test.d.ts +0 -1
  223. package/dist/transformers.test.js +0 -423
  224. package/dist/utils.test.d.ts +0 -1
  225. package/dist/utils.test.js +0 -242
  226. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -2221,6 +2221,163 @@ describe("startChangeStreamWatcher", () => {
2221
2221
  mockStream.trigger("end");
2222
2222
  });
2223
2223
 
2224
+ // Task 9.16: a transient stream failure used to be logged and then permanently starve
2225
+ // every realtime event and sync delta until the process restarted.
2226
+ describe("restart with resume token (Task 9.16)", () => {
2227
+ const waitFor = async (
2228
+ predicate: () => boolean,
2229
+ label: string,
2230
+ timeoutMs = 3000
2231
+ ): Promise<void> => {
2232
+ const start = Date.now();
2233
+ while (Date.now() - start < timeoutMs) {
2234
+ if (predicate()) {
2235
+ return;
2236
+ }
2237
+ await new Promise((resolve) => setTimeout(resolve, 10));
2238
+ }
2239
+ throw new Error(`Timed out after ${timeoutMs}ms waiting for ${label}`);
2240
+ };
2241
+
2242
+ const registerTodos = (): void => {
2243
+ registerRealtime({
2244
+ collectionName: "todos",
2245
+ config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
2246
+ modelName: "Todo",
2247
+ options: {
2248
+ permissions: {
2249
+ create: [() => true],
2250
+ delete: [() => true],
2251
+ list: [() => true],
2252
+ read: [() => true],
2253
+ update: [() => true],
2254
+ },
2255
+ },
2256
+ routePath: "/todos",
2257
+ });
2258
+ };
2259
+
2260
+ /** An io whose room socket records deliveries, plus a recorded server-wide `emit`. */
2261
+ const createRecordingIo = (): {
2262
+ io: import("socket.io").Server;
2263
+ deliveries: {event: string; payload: unknown}[];
2264
+ serverEmissions: {event: string; payload: unknown}[];
2265
+ } => {
2266
+ const deliveries: {event: string; payload: unknown}[] = [];
2267
+ const serverEmissions: {event: string; payload: unknown}[] = [];
2268
+ const rooms = new Map<string, Set<string>>();
2269
+ rooms.set("model:todos", new Set(["sock-1"]));
2270
+ const sockets = new Map<string, any>();
2271
+ sockets.set("sock-1", {
2272
+ decodedToken: {id: "user-1"},
2273
+ emit: (event: string, payload: unknown) => {
2274
+ deliveries.push({event, payload});
2275
+ },
2276
+ id: "sock-1",
2277
+ });
2278
+ return {
2279
+ deliveries,
2280
+ io: {
2281
+ emit: (event: string, payload: unknown) => {
2282
+ serverEmissions.push({event, payload});
2283
+ },
2284
+ sockets: {adapter: {rooms}, sockets},
2285
+ to: () => ({emit: () => {}}),
2286
+ } as unknown as import("socket.io").Server,
2287
+ serverEmissions,
2288
+ };
2289
+ };
2290
+
2291
+ it("reopens with resumeAfter after a stream error and keeps delivering changes", async () => {
2292
+ const firstStream = createMockChangeStream();
2293
+ const secondStream = createMockChangeStream();
2294
+ const streams = [firstStream, secondStream];
2295
+ const mockDb = {watch: mock(() => streams.shift() ?? secondStream)};
2296
+ (mongoose.connection as any).db = mockDb;
2297
+ registerTodos();
2298
+
2299
+ const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
2300
+ const {deliveries, io} = createRecordingIo();
2301
+ startChangeStreamWatcher(io, {}, true);
2302
+
2303
+ // A change on the first stream establishes the resume position.
2304
+ await invokeRegisteredChangeHandler(firstStream, {
2305
+ _id: {_data: "token-1"},
2306
+ documentKey: {_id: "doc-1"},
2307
+ fullDocument: {_id: "doc-1", name: "before the failure"},
2308
+ ns: {coll: "todos"},
2309
+ operationType: "insert",
2310
+ });
2311
+ expect(deliveries).toHaveLength(1);
2312
+
2313
+ firstStream.trigger("error", new Error("replica set election"));
2314
+ await waitFor(() => mockDb.watch.mock.calls.length >= 2, "the stream to reopen");
2315
+
2316
+ const reopenOptions = (mockDb.watch.mock.calls[1] as any[])[1];
2317
+ expect(reopenOptions.resumeAfter).toEqual({_data: "token-1"});
2318
+
2319
+ // The reopened stream is fully wired: later writes still fan out.
2320
+ await invokeRegisteredChangeHandler(secondStream, {
2321
+ _id: {_data: "token-2"},
2322
+ documentKey: {_id: "doc-2"},
2323
+ fullDocument: {_id: "doc-2", name: "after the restart"},
2324
+ ns: {coll: "todos"},
2325
+ operationType: "insert",
2326
+ });
2327
+ expect(deliveries).toHaveLength(2);
2328
+ });
2329
+
2330
+ it("drops the resume token and asks clients to resync when the oplog history is lost", async () => {
2331
+ const firstStream = createMockChangeStream();
2332
+ const secondStream = createMockChangeStream();
2333
+ const streams = [firstStream, secondStream];
2334
+ const mockDb = {watch: mock(() => streams.shift() ?? secondStream)};
2335
+ (mongoose.connection as any).db = mockDb;
2336
+
2337
+ const {SYNC_RESYNC_EVENT, startChangeStreamWatcher} = await import("./changeStreamWatcher");
2338
+ const {io, serverEmissions} = createRecordingIo();
2339
+ startChangeStreamWatcher(io, {}, true);
2340
+
2341
+ await invokeRegisteredChangeHandler(firstStream, {
2342
+ _id: {_data: "token-1"},
2343
+ documentKey: {_id: "doc-1"},
2344
+ ns: {coll: "unregistered"},
2345
+ operationType: "insert",
2346
+ });
2347
+
2348
+ const historyLost = Object.assign(new Error("resume of change stream was not possible"), {
2349
+ code: 286,
2350
+ codeName: "ChangeStreamHistoryLost",
2351
+ });
2352
+ firstStream.trigger("error", historyLost);
2353
+
2354
+ expect(serverEmissions).toEqual([
2355
+ {event: SYNC_RESYNC_EVENT, payload: {reason: "history_lost"}},
2356
+ ]);
2357
+
2358
+ await waitFor(() => mockDb.watch.mock.calls.length >= 2, "the stream to reopen");
2359
+ // An unusable token must not be replayed — the reopen starts from now.
2360
+ expect((mockDb.watch.mock.calls[1] as any[])[1].resumeAfter).toBeUndefined();
2361
+ });
2362
+
2363
+ it("does not reopen after the watcher is stopped", async () => {
2364
+ const mockStream = createMockChangeStream();
2365
+ const mockDb = {watch: mock(() => mockStream)};
2366
+ (mongoose.connection as any).db = mockDb;
2367
+
2368
+ const {startChangeStreamWatcher, stopChangeStreamWatcher: stop} = await import(
2369
+ "./changeStreamWatcher"
2370
+ );
2371
+ const {io} = createRecordingIo();
2372
+ startChangeStreamWatcher(io, {}, true);
2373
+
2374
+ mockStream.trigger("error", new Error("shutting down"));
2375
+ await stop();
2376
+ await new Promise((resolve) => setTimeout(resolve, 400));
2377
+ expect(mockDb.watch).toHaveBeenCalledTimes(1);
2378
+ });
2379
+ });
2380
+
2224
2381
  it("uses custom batchSize and fullDocument config", async () => {
2225
2382
  const mockStream = createMockChangeStream();
2226
2383
  const mockDb = {
@@ -2,13 +2,15 @@
2
2
  // biome-ignore-all lint/suspicious/noExplicitAny: Socket.io handler signatures require dynamic args
3
3
  import type http from "node:http";
4
4
  import * as Sentry from "@sentry/bun";
5
- import {authorize} from "@thream/socketio-jwt";
6
5
  import type express from "express";
7
6
  import {Server, type Socket} from "socket.io";
8
7
 
9
8
  import type {User} from "../auth";
10
9
  import {logger} from "../logger";
11
10
  import {checkPermissions} from "../permissions";
11
+ import {warnOnSyncScopesWithoutUserModel} from "../sync/registry";
12
+ import {installSyncSocketHandlers} from "../sync/socketHandlers";
13
+ import {getSyncAppOptions} from "../sync/syncApp";
12
14
  import type {TerrenoPlugin} from "../terrenoPlugin";
13
15
  import {startChangeStreamWatcher, stopChangeStreamWatcher} from "./changeStreamWatcher";
14
16
  import {
@@ -18,7 +20,13 @@ import {
18
20
  removeQuerySubscription,
19
21
  } from "./queryStore";
20
22
  import {findRegistryEntryByRoutePath, type RealtimeRegistryEntry} from "./registry";
21
- import {getSocketUser, type SocketWithDecodedToken} from "./socketUser";
23
+ import {
24
+ loadFullUserForSocket,
25
+ type SessionRevalidationHandle,
26
+ startSessionRevalidationSweep,
27
+ } from "./sessionRevalidation";
28
+ import {createSocketAuthMiddleware} from "./socketAuth";
29
+ import {getSocketUser, type SocketDataBag, type SocketWithDecodedToken} from "./socketUser";
22
30
  import type {DocumentSubscription, QuerySubscription, RealtimeAppOptions} from "./types";
23
31
 
24
32
  /**
@@ -122,7 +130,9 @@ export const installRealtimeSocketHandlers = (
122
130
  const logInfo = options.logInfo ?? ((): void => {});
123
131
  const userId = socket.decodedToken?.id;
124
132
  const isAdmin = socket.decodedToken?.admin === true;
125
- const user = getSocketUser(socket);
133
+ // D2: re-derive per event rather than capturing once at install time, so a
134
+ // handshake-time-loaded full user (or one refreshed by D1's sweep) is always used.
135
+ const currentUser = (): User | undefined => getSocketUser(socket);
126
136
 
127
137
  const counts = {document: 0, model: 0, query: 0};
128
138
 
@@ -169,7 +179,7 @@ export const installRealtimeSocketHandlers = (
169
179
  return;
170
180
  }
171
181
 
172
- if (!(await canSubscribe(entry, "list", user))) {
182
+ if (!(await canSubscribe(entry, "list", currentUser()))) {
173
183
  logInfo(
174
184
  `[realtime] User ${userId} denied model subscription for ${modelName}: list permission denied`
175
185
  );
@@ -212,7 +222,7 @@ export const installRealtimeSocketHandlers = (
212
222
  return;
213
223
  }
214
224
 
215
- if (!(await canSubscribe(entry, "read", user))) {
225
+ if (!(await canSubscribe(entry, "read", currentUser()))) {
216
226
  logInfo(
217
227
  `[realtime] User ${userId} denied document subscription for ` +
218
228
  `${payload.collection}/${payload.id}: read permission denied`
@@ -267,7 +277,7 @@ export const installRealtimeSocketHandlers = (
267
277
  return;
268
278
  }
269
279
 
270
- let query = await getAuthorizedQuery(entry, {...payload.query}, user);
280
+ let query = await getAuthorizedQuery(entry, {...payload.query}, currentUser());
271
281
  if (!query) {
272
282
  logInfo(
273
283
  `[realtime] User ${userId} denied query subscription for ${payload.collection}: ` +
@@ -336,8 +346,10 @@ export const installRealtimeSocketHandlers = (
336
346
  * ```
337
347
  */
338
348
  export class RealtimeApp implements TerrenoPlugin {
349
+ private app: express.Application | null = null;
339
350
  private io: Server | null = null;
340
351
  private config: RealtimeAppOptions;
352
+ private sessionRevalidation: SessionRevalidationHandle | null = null;
341
353
 
342
354
  constructor(config: RealtimeAppOptions = {}) {
343
355
  this.config = config;
@@ -347,6 +359,7 @@ export class RealtimeApp implements TerrenoPlugin {
347
359
  * Register routes and middleware. Adds a /realtime/health endpoint.
348
360
  */
349
361
  register(app: express.Application): void {
362
+ this.app = app;
350
363
  app.get("/realtime/health", (_req, res) => {
351
364
  const connected = this.io?.engine?.clientsCount ?? 0;
352
365
  res.json({
@@ -380,7 +393,7 @@ export class RealtimeApp implements TerrenoPlugin {
380
393
  },
381
394
  });
382
395
 
383
- // JWT authentication middleware
396
+ // Authentication middleware: legacy JWT first, optionally Better Auth sessions.
384
397
  const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
385
398
  if (!tokenSecret) {
386
399
  throw new Error(
@@ -389,13 +402,31 @@ export class RealtimeApp implements TerrenoPlugin {
389
402
  );
390
403
  }
391
404
 
405
+ // D1: pass the issuer through for parity with the HTTP JWT path
406
+ // (jwt.verify(token, secret, {issuer})) — without it a validly-signed token
407
+ // issued for a different TOKEN_ISSUER was silently accepted over sockets. A
408
+ // thunk (not a value captured once here) so a later change to
409
+ // process.env.TOKEN_ISSUER — or to an explicitly configured tokenIssuer — is
410
+ // honored on every handshake, matching the HTTP path's per-request env read.
411
+ const resolveTokenIssuer = (): string | undefined =>
412
+ this.config.tokenIssuer ?? process.env.TOKEN_ISSUER;
413
+
392
414
  this.io.use(
393
- authorize({
394
- secret: tokenSecret,
415
+ createSocketAuthMiddleware({
416
+ betterAuth: this.config.betterAuth,
417
+ issuer: resolveTokenIssuer,
418
+ tokenSecret,
395
419
  })
396
420
  );
397
421
 
398
- logInfo("[realtime] JWT authorization middleware added");
422
+ logInfo(
423
+ `[realtime] Socket auth middleware added (JWT${this.config.betterAuth ? " + Better Auth" : ""})`
424
+ );
425
+
426
+ // Task 9.21: tenant/custom sync scopes can only be resolved from the full user
427
+ // document, so warn loudly here (once, at startup) rather than silently serving
428
+ // empty tenant streams for the life of the process.
429
+ warnOnSyncScopesWithoutUserModel({userModel: this.config.userModel});
399
430
 
400
431
  // Configure adapter for multi-instance deployments
401
432
  this.setupAdapter(logInfo);
@@ -403,9 +434,27 @@ export class RealtimeApp implements TerrenoPlugin {
403
434
  // Connection handling
404
435
  this.io.on("connection", (socket: Socket): void => {
405
436
  try {
406
- // socketio-jwt's authorize middleware adds `decodedToken` at runtime; cast through
437
+ // D2: load the full user document once at handshake (by the decoded
438
+ // token's id) and cache it on socket.data.fullUser — getSocketUser prefers
439
+ // it over the synthetic {_id, admin, id} shape for every authorization
440
+ // check below. Fire-and-forget: handlers install synchronously and fall
441
+ // back to the synthetic shape until this resolves.
442
+ void loadFullUserForSocket(
443
+ socket as unknown as Socket & {data: SocketDataBag},
444
+ this.config.userModel
445
+ );
446
+ // The auth middleware adds `decodedToken` at runtime; cast through
407
447
  // RealtimeSocketLike (a structural subset) to keep socket handler logic testable.
408
448
  installRealtimeSocketHandlers(socket as unknown as RealtimeSocketLike, {logInfo});
449
+ // Sync protocol handlers (sync:subscribe / sync:mutate). Options come from the
450
+ // SyncApp registered on this Express app or an explicit `sync` override here;
451
+ // with neither, the handlers still install and reject unknown collections.
452
+ installSyncSocketHandlers(
453
+ this.io,
454
+ socket as unknown as RealtimeSocketLike,
455
+ this.config.sync ?? (this.app ? getSyncAppOptions(this.app) : undefined) ?? {},
456
+ {logInfo}
457
+ );
409
458
  } catch (error) {
410
459
  logger.error(`[realtime] Error handling connection: ${error}`);
411
460
  Sentry.captureException(error);
@@ -420,6 +469,19 @@ export class RealtimeApp implements TerrenoPlugin {
420
469
  // Start the change stream watcher
421
470
  startChangeStreamWatcher(this.io, this.config.changeStream, debug);
422
471
 
472
+ // D1: periodic session re-validation sweep — disconnects sockets whose JWT has
473
+ // expired, whose Better Auth session is no longer valid, or whose user has
474
+ // since been disabled; also refreshes socket.data.fullUser (D2) and
475
+ // re-resolves sync room membership (D4) for sockets that remain valid.
476
+ // A thunk (not a snapshot) reads this app's SyncApp options fresh on every sweep.
477
+ this.sessionRevalidation = startSessionRevalidationSweep(this.io, () => ({
478
+ betterAuth: this.config.betterAuth,
479
+ intervalMs: this.config.sessionRevalidationIntervalMs,
480
+ logInfo,
481
+ sync: this.config.sync ?? (this.app ? getSyncAppOptions(this.app) : undefined),
482
+ userModel: this.config.userModel,
483
+ }));
484
+
423
485
  logInfo("[realtime] Socket.io server setup complete");
424
486
  } catch (error) {
425
487
  logger.error(`[realtime] Failed to set up Socket.io: ${error}`);
@@ -440,6 +502,8 @@ export class RealtimeApp implements TerrenoPlugin {
440
502
  */
441
503
  async close(): Promise<void> {
442
504
  try {
505
+ this.sessionRevalidation?.stop();
506
+ this.sessionRevalidation = null;
443
507
  await stopChangeStreamWatcher();
444
508
  if (this.io) {
445
509
  await this.io.close();