@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
@@ -46,10 +46,8 @@ import {
46
46
  findRegistryEntryByCollection,
47
47
  findRegistryEntryByRoutePath,
48
48
  getRealtimeRegistry,
49
- type RealtimeRegistryEntry,
50
49
  registerRealtime,
51
50
  } from "./registry";
52
- import type {RealtimeEvent} from "./types";
53
51
 
54
52
  // ─────────────────────────────────────────────────────────────────────────────
55
53
  // queryMatcher tests
@@ -1770,123 +1768,6 @@ describe("emitToDocumentAndQueryRooms", () => {
1770
1768
 
1771
1769
  expect(emissions).toEqual([]);
1772
1770
  });
1773
-
1774
- describe("query room fanout with a registry entry", () => {
1775
- const modelEntry: RealtimeRegistryEntry = {
1776
- collectionName: "todos",
1777
- config: {methods: ["create", "update", "delete"], roomStrategy: "model"},
1778
- modelName: "Todo",
1779
- options: {
1780
- permissions: {
1781
- create: [() => true],
1782
- delete: [() => true],
1783
- list: [() => true],
1784
- read: [() => true],
1785
- update: [() => true],
1786
- },
1787
- },
1788
- routePath: "/todos",
1789
- };
1790
-
1791
- const makeEvent = (method: RealtimeEvent["method"]): RealtimeEvent => ({
1792
- collection: "todos",
1793
- id: "doc-1",
1794
- method,
1795
- model: "Todo",
1796
- timestamp: 1,
1797
- });
1798
-
1799
- it("emits creates through the permission-filtered path", async () => {
1800
- const queryId = computeQueryId("todos", {priority: 1});
1801
- addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1802
- const {addSocketToRoom, emissions, io} = makeIo();
1803
- addSocketToRoom(`query:${queryId}`, {id: "user-1"});
1804
-
1805
- await emitToDocumentAndQueryRooms(
1806
- io,
1807
- "todos",
1808
- makeEvent("create"),
1809
- {priority: 1},
1810
- () => {},
1811
- modelEntry
1812
- );
1813
-
1814
- const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
1815
- expect(queryEmissions).toHaveLength(1);
1816
- expect(queryEmissions[0].payload).toMatchObject({data: {priority: 1}, method: "create"});
1817
- });
1818
-
1819
- it("emits updates through the permission-filtered path when the doc still matches", async () => {
1820
- const queryId = computeQueryId("todos", {priority: 1});
1821
- addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1822
- const {addSocketToRoom, emissions, io} = makeIo();
1823
- addSocketToRoom(`query:${queryId}`, {id: "user-1"});
1824
-
1825
- await emitToDocumentAndQueryRooms(
1826
- io,
1827
- "todos",
1828
- makeEvent("update"),
1829
- {priority: 1},
1830
- () => {},
1831
- modelEntry
1832
- );
1833
-
1834
- const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
1835
- expect(queryEmissions).toHaveLength(1);
1836
- expect(queryEmissions[0].payload).toMatchObject({method: "update"});
1837
- });
1838
-
1839
- it("converts non-matching updates into deletes through the permission-filtered path", async () => {
1840
- const queryId = computeQueryId("todos", {priority: 1});
1841
- addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1842
- const {addSocketToRoom, emissions, io} = makeIo();
1843
- addSocketToRoom(`query:${queryId}`, {id: "user-1"});
1844
-
1845
- await emitToDocumentAndQueryRooms(
1846
- io,
1847
- "todos",
1848
- makeEvent("update"),
1849
- {priority: 9},
1850
- () => {},
1851
- modelEntry
1852
- );
1853
-
1854
- const queryEmissions = emissions.filter((e) => e.room === `query:${queryId}`);
1855
- expect(queryEmissions).toHaveLength(1);
1856
- expect(queryEmissions[0].payload).toMatchObject({method: "delete"});
1857
- });
1858
-
1859
- it("skips query rooms whose subscribers cannot read the document", async () => {
1860
- const queryId = computeQueryId("todos", {priority: 1});
1861
- addQuerySubscription("socket-a", "todos", {priority: 1}, queryId);
1862
- const {addSocketToRoom, emissions, io} = makeIo();
1863
- addSocketToRoom(`query:${queryId}`, {id: "other-user"});
1864
- const ownerEntry: RealtimeRegistryEntry = {
1865
- ...modelEntry,
1866
- options: {
1867
- permissions: {
1868
- ...modelEntry.options.permissions,
1869
- read: [
1870
- (_method, user?: {admin?: boolean; id?: string}, obj?: unknown) =>
1871
- user?.admin === true ||
1872
- user?.id === (obj as {ownerId?: string} | undefined)?.ownerId,
1873
- ],
1874
- },
1875
- },
1876
- };
1877
-
1878
- await emitToDocumentAndQueryRooms(
1879
- io,
1880
- "todos",
1881
- makeEvent("create"),
1882
- {ownerId: "user-1", priority: 1},
1883
- () => {},
1884
- ownerEntry
1885
- );
1886
-
1887
- expect(emissions.some((e) => e.room === `query:${queryId}`)).toBe(false);
1888
- });
1889
- });
1890
1771
  });
1891
1772
 
1892
1773
  // ─────────────────────────────────────────────────────────────────────────────
@@ -2178,126 +2059,6 @@ describe("startChangeStreamWatcher", () => {
2178
2059
  });
2179
2060
  });
2180
2061
 
2181
- // Records every emission so hard-delete room routing can be asserted.
2182
- const createRecordingIo = (
2183
- room: string,
2184
- decodedToken: {admin?: boolean; id?: string} = {admin: true, id: "admin"}
2185
- ): {
2186
- emissions: Array<{event: string; payload: unknown}>;
2187
- io: import("socket.io").Server;
2188
- } => {
2189
- const emissions: Array<{event: string; payload: unknown}> = [];
2190
- const rooms = new Map<string, Set<string>>([[room, new Set(["socket-1"])]]);
2191
- const sockets = new Map<string, unknown>([
2192
- [
2193
- "socket-1",
2194
- {
2195
- decodedToken,
2196
- emit: (event: string, payload: unknown): void => {
2197
- emissions.push({event, payload});
2198
- },
2199
- id: "socket-1",
2200
- },
2201
- ],
2202
- ]);
2203
- return {
2204
- emissions,
2205
- io: {
2206
- sockets: {adapter: {rooms}, sockets},
2207
- to: (_room: string) => ({emit: (_event: string, _data: unknown) => {}}),
2208
- } as unknown as import("socket.io").Server,
2209
- };
2210
- };
2211
-
2212
- it("routes hard deletes for model-strategy models to the model room", async () => {
2213
- const mockStream = createMockChangeStream();
2214
- const mockDb = {
2215
- watch: mock(() => mockStream),
2216
- };
2217
- (mongoose.connection as unknown as {db: unknown}).db = mockDb;
2218
-
2219
- registerRealtime({
2220
- collectionName: "todos",
2221
- config: {
2222
- methods: ["create", "update", "delete"],
2223
- roomStrategy: "model",
2224
- },
2225
- modelName: "Todo",
2226
- options: {
2227
- permissions: {
2228
- create: [() => true],
2229
- delete: [() => true],
2230
- list: [() => true],
2231
- read: [() => true],
2232
- update: [() => true],
2233
- },
2234
- },
2235
- routePath: "/todos",
2236
- });
2237
-
2238
- const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
2239
- const {emissions, io} = createRecordingIo("model:todos");
2240
-
2241
- startChangeStreamWatcher(io, {}, true);
2242
-
2243
- await invokeRegisteredChangeHandler(mockStream, {
2244
- documentKey: {_id: "doc-1"},
2245
- ns: {coll: "todos"},
2246
- operationType: "delete",
2247
- });
2248
-
2249
- expect(emissions).toHaveLength(1);
2250
- expect(emissions[0].payload).toMatchObject({id: "doc-1", method: "delete", model: "Todo"});
2251
- });
2252
-
2253
- it("swallows errors thrown while processing a change event", async () => {
2254
- const mockStream = createMockChangeStream();
2255
- const mockDb = {
2256
- watch: mock(() => mockStream),
2257
- };
2258
- (mongoose.connection as unknown as {db: unknown}).db = mockDb;
2259
-
2260
- registerRealtime({
2261
- collectionName: "todos",
2262
- config: {
2263
- methods: ["create", "update", "delete"],
2264
- roomStrategy: "model",
2265
- },
2266
- modelName: "Todo",
2267
- options: {
2268
- permissions: {
2269
- create: [() => true],
2270
- delete: [() => true],
2271
- list: [() => true],
2272
- read: [() => true],
2273
- update: [() => true],
2274
- },
2275
- },
2276
- routePath: "/todos",
2277
- });
2278
-
2279
- const {startChangeStreamWatcher} = await import("./changeStreamWatcher");
2280
- const roomLookup = mock(() => {
2281
- throw new Error("adapter unavailable");
2282
- });
2283
- const io = {
2284
- sockets: {adapter: {rooms: {get: roomLookup}}, sockets: new Map()},
2285
- to: (_room: string) => ({emit: (_event: string, _data: unknown) => {}}),
2286
- } as unknown as import("socket.io").Server;
2287
-
2288
- startChangeStreamWatcher(io, {}, true);
2289
-
2290
- // The handler must not reject — a failed emission cannot take down the change stream.
2291
- await invokeRegisteredChangeHandler(mockStream, {
2292
- documentKey: {_id: "doc-1"},
2293
- fullDocument: {_id: "doc-1", name: "Test Todo"},
2294
- ns: {coll: "todos"},
2295
- operationType: "insert",
2296
- });
2297
-
2298
- expect(roomLookup).toHaveBeenCalled();
2299
- });
2300
-
2301
2062
  it("includes updatedFields in event for update operations", async () => {
2302
2063
  const mockStream = createMockChangeStream();
2303
2064
  const mockDb = {
@@ -2460,6 +2221,163 @@ describe("startChangeStreamWatcher", () => {
2460
2221
  mockStream.trigger("end");
2461
2222
  });
2462
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
+
2463
2381
  it("uses custom batchSize and fullDocument config", async () => {
2464
2382
  const mockStream = createMockChangeStream();
2465
2383
  const mockDb = {
@@ -2,14 +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
- import {APIError} from "../errors";
11
9
  import {logger} from "../logger";
12
10
  import {checkPermissions} from "../permissions";
11
+ import {warnOnSyncScopesWithoutUserModel} from "../sync/registry";
12
+ import {installSyncSocketHandlers} from "../sync/socketHandlers";
13
+ import {getSyncAppOptions} from "../sync/syncApp";
13
14
  import type {TerrenoPlugin} from "../terrenoPlugin";
14
15
  import {startChangeStreamWatcher, stopChangeStreamWatcher} from "./changeStreamWatcher";
15
16
  import {
@@ -19,7 +20,13 @@ import {
19
20
  removeQuerySubscription,
20
21
  } from "./queryStore";
21
22
  import {findRegistryEntryByRoutePath, type RealtimeRegistryEntry} from "./registry";
22
- 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";
23
30
  import type {DocumentSubscription, QuerySubscription, RealtimeAppOptions} from "./types";
24
31
 
25
32
  /**
@@ -62,7 +69,7 @@ export interface RealtimeSocketLike extends SocketWithDecodedToken {
62
69
  join: (room: string) => Promise<void> | void;
63
70
  leave: (room: string) => Promise<void> | void;
64
71
  emit: (event: string, payload: unknown) => void;
65
- on: (event: string, handler: (...args: never[]) => void | Promise<void>) => void;
72
+ on: (event: string, handler: (...args: any[]) => any) => void;
66
73
  }
67
74
 
68
75
  const canSubscribe = async (
@@ -123,7 +130,9 @@ export const installRealtimeSocketHandlers = (
123
130
  const logInfo = options.logInfo ?? ((): void => {});
124
131
  const userId = socket.decodedToken?.id;
125
132
  const isAdmin = socket.decodedToken?.admin === true;
126
- 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);
127
136
 
128
137
  const counts = {document: 0, model: 0, query: 0};
129
138
 
@@ -170,7 +179,7 @@ export const installRealtimeSocketHandlers = (
170
179
  return;
171
180
  }
172
181
 
173
- if (!(await canSubscribe(entry, "list", user))) {
182
+ if (!(await canSubscribe(entry, "list", currentUser()))) {
174
183
  logInfo(
175
184
  `[realtime] User ${userId} denied model subscription for ${modelName}: list permission denied`
176
185
  );
@@ -213,7 +222,7 @@ export const installRealtimeSocketHandlers = (
213
222
  return;
214
223
  }
215
224
 
216
- if (!(await canSubscribe(entry, "read", user))) {
225
+ if (!(await canSubscribe(entry, "read", currentUser()))) {
217
226
  logInfo(
218
227
  `[realtime] User ${userId} denied document subscription for ` +
219
228
  `${payload.collection}/${payload.id}: read permission denied`
@@ -268,7 +277,7 @@ export const installRealtimeSocketHandlers = (
268
277
  return;
269
278
  }
270
279
 
271
- let query = await getAuthorizedQuery(entry, {...payload.query}, user);
280
+ let query = await getAuthorizedQuery(entry, {...payload.query}, currentUser());
272
281
  if (!query) {
273
282
  logInfo(
274
283
  `[realtime] User ${userId} denied query subscription for ${payload.collection}: ` +
@@ -337,8 +346,10 @@ export const installRealtimeSocketHandlers = (
337
346
  * ```
338
347
  */
339
348
  export class RealtimeApp implements TerrenoPlugin {
349
+ private app: express.Application | null = null;
340
350
  private io: Server | null = null;
341
351
  private config: RealtimeAppOptions;
352
+ private sessionRevalidation: SessionRevalidationHandle | null = null;
342
353
 
343
354
  constructor(config: RealtimeAppOptions = {}) {
344
355
  this.config = config;
@@ -348,6 +359,7 @@ export class RealtimeApp implements TerrenoPlugin {
348
359
  * Register routes and middleware. Adds a /realtime/health endpoint.
349
360
  */
350
361
  register(app: express.Application): void {
362
+ this.app = app;
351
363
  app.get("/realtime/health", (_req, res) => {
352
364
  const connected = this.io?.engine?.clientsCount ?? 0;
353
365
  res.json({
@@ -381,24 +393,40 @@ export class RealtimeApp implements TerrenoPlugin {
381
393
  },
382
394
  });
383
395
 
384
- // JWT authentication middleware
396
+ // Authentication middleware: legacy JWT first, optionally Better Auth sessions.
385
397
  const tokenSecret = this.config.tokenSecret ?? process.env.TOKEN_SECRET;
386
398
  if (!tokenSecret) {
387
- throw new APIError({
388
- status: 500,
389
- title:
390
- "[realtime] TOKEN_SECRET is required for socket authentication. " +
391
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
392
- });
399
+ throw new Error(
400
+ "[realtime] TOKEN_SECRET is required for socket authentication. " +
401
+ "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions."
402
+ );
393
403
  }
394
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
+
395
414
  this.io.use(
396
- authorize({
397
- secret: tokenSecret,
415
+ createSocketAuthMiddleware({
416
+ betterAuth: this.config.betterAuth,
417
+ issuer: resolveTokenIssuer,
418
+ tokenSecret,
398
419
  })
399
420
  );
400
421
 
401
- 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});
402
430
 
403
431
  // Configure adapter for multi-instance deployments
404
432
  this.setupAdapter(logInfo);
@@ -406,9 +434,27 @@ export class RealtimeApp implements TerrenoPlugin {
406
434
  // Connection handling
407
435
  this.io.on("connection", (socket: Socket): void => {
408
436
  try {
409
- // 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
410
447
  // RealtimeSocketLike (a structural subset) to keep socket handler logic testable.
411
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
+ );
412
458
  } catch (error) {
413
459
  logger.error(`[realtime] Error handling connection: ${error}`);
414
460
  Sentry.captureException(error);
@@ -423,6 +469,19 @@ export class RealtimeApp implements TerrenoPlugin {
423
469
  // Start the change stream watcher
424
470
  startChangeStreamWatcher(this.io, this.config.changeStream, debug);
425
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
+
426
485
  logInfo("[realtime] Socket.io server setup complete");
427
486
  } catch (error) {
428
487
  logger.error(`[realtime] Failed to set up Socket.io: ${error}`);
@@ -443,6 +502,8 @@ export class RealtimeApp implements TerrenoPlugin {
443
502
  */
444
503
  async close(): Promise<void> {
445
504
  try {
505
+ this.sessionRevalidation?.stop();
506
+ this.sessionRevalidation = null;
446
507
  await stopChangeStreamWatcher();
447
508
  if (this.io) {
448
509
  await this.io.close();