@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
@@ -0,0 +1,423 @@
1
+ // noExplicitAny: test mocks use dynamic shapes for sockets, io, and models
2
+ // biome-ignore-all lint/suspicious/noExplicitAny: test mocks use dynamic shapes for sockets, io, and models
3
+ /**
4
+ * D1: socket session re-validation sweep.
5
+ * - revalidateSocketSession: expired/disabled/invalid-session detection per auth kind
6
+ * - reresolveSyncRoomsForSocket: D4 room membership diffing (leave revoked, join granted)
7
+ * - runSessionRevalidationSweep: disconnects failing sockets with sync:auth-expired
8
+ * - loadFullUserForSocket: D2 handshake full-user load
9
+ */
10
+ import {afterEach, describe, expect, it, mock} from "bun:test";
11
+ import {DateTime} from "luxon";
12
+ import mongoose, {model, Schema} from "mongoose";
13
+
14
+ import {createdUpdatedPlugin, isDeletedPlugin} from "../plugins";
15
+ import {clearSyncRegistry, registerSync} from "../sync/registry";
16
+ import {syncPlugin} from "../sync/syncSeqPlugin";
17
+ import {
18
+ loadFullUserForSocket,
19
+ type RevalidatableSocket,
20
+ reresolveSyncRoomsForSocket,
21
+ revalidateSocketSession,
22
+ runSessionRevalidationSweep,
23
+ startSessionRevalidationSweep,
24
+ } from "./sessionRevalidation";
25
+
26
+ /** Minimal fake Mongoose model: findOneOrNoneFor falls back to `.find()` without the plugin. */
27
+ const fakeUserModel = (users: Record<string, unknown>): any => ({
28
+ find: async (query: {_id: string}) => {
29
+ const user = users[query._id];
30
+ return user ? [user] : [];
31
+ },
32
+ });
33
+
34
+ /**
35
+ * Real (but never persisted — no test DB round-trip needed) Mongoose models satisfying
36
+ * `registerSync`'s schema contract (soft delete + syncPlugin + scope field present), so
37
+ * D4's room-resolution tests can register genuine sync registry entries.
38
+ */
39
+ const revalTenantSchema = new Schema({
40
+ organizationId: {type: String},
41
+ title: {type: String},
42
+ });
43
+ revalTenantSchema.plugin(isDeletedPlugin);
44
+ revalTenantSchema.plugin(createdUpdatedPlugin);
45
+ revalTenantSchema.plugin(syncPlugin);
46
+ const RevalTenantModel =
47
+ (mongoose.models.RevalSessionProject as mongoose.Model<any>) ||
48
+ model("RevalSessionProject", revalTenantSchema);
49
+
50
+ const revalOwnerSchema = new Schema({
51
+ ownerId: {type: String},
52
+ title: {type: String},
53
+ });
54
+ revalOwnerSchema.plugin(isDeletedPlugin);
55
+ revalOwnerSchema.plugin(createdUpdatedPlugin);
56
+ revalOwnerSchema.plugin(syncPlugin);
57
+ const RevalOwnerModel =
58
+ (mongoose.models.RevalSessionTodo as mongoose.Model<any>) ||
59
+ model("RevalSessionTodo", revalOwnerSchema);
60
+
61
+ const makeSocket = (overrides: Partial<RevalidatableSocket> = {}): RevalidatableSocket => ({
62
+ data: {},
63
+ disconnect: mock(() => {}),
64
+ emit: mock(() => {}),
65
+ id: "socket-1",
66
+ join: mock(async () => {}),
67
+ leave: mock(async () => {}),
68
+ ...overrides,
69
+ });
70
+
71
+ describe("revalidateSocketSession", () => {
72
+ it("returns valid for a JWT socket whose exp is in the future", async () => {
73
+ const socket = makeSocket({
74
+ decodedToken: {
75
+ authKind: "jwt",
76
+ exp: DateTime.now().plus({minutes: 10}).toSeconds(),
77
+ id: "u1",
78
+ },
79
+ });
80
+ const outcome = await revalidateSocketSession(socket, {});
81
+ expect(outcome).toBe("valid");
82
+ });
83
+
84
+ it("returns expired for a JWT socket whose exp has passed", async () => {
85
+ const socket = makeSocket({
86
+ decodedToken: {
87
+ authKind: "jwt",
88
+ exp: DateTime.now().minus({minutes: 1}).toSeconds(),
89
+ id: "u1",
90
+ },
91
+ });
92
+ const outcome = await revalidateSocketSession(socket, {});
93
+ expect(outcome).toBe("expired");
94
+ });
95
+
96
+ it("treats a JWT socket with no exp claim as valid (nothing to check locally)", async () => {
97
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "u1"}});
98
+ const outcome = await revalidateSocketSession(socket, {});
99
+ expect(outcome).toBe("valid");
100
+ });
101
+
102
+ it("returns valid for a Better Auth socket whose session lookup still resolves", async () => {
103
+ const socket = makeSocket({
104
+ decodedToken: {authKind: "better-auth", id: "u1"},
105
+ encodedToken: "session-token",
106
+ });
107
+ const outcome = await revalidateSocketSession(socket, {
108
+ betterAuth: {
109
+ auth: {api: {getSession: async () => ({user: {id: "u1"}})}} as any,
110
+ },
111
+ });
112
+ expect(outcome).toBe("valid");
113
+ });
114
+
115
+ it("returns invalid-session for a Better Auth socket whose session no longer resolves", async () => {
116
+ const socket = makeSocket({
117
+ decodedToken: {authKind: "better-auth", id: "u1"},
118
+ encodedToken: "revoked-session-token",
119
+ });
120
+ const outcome = await revalidateSocketSession(socket, {
121
+ betterAuth: {auth: {api: {getSession: async () => null}} as any},
122
+ });
123
+ expect(outcome).toBe("invalid-session");
124
+ });
125
+
126
+ it("returns invalid-session for a Better Auth socket when no betterAuth options are configured", async () => {
127
+ const socket = makeSocket({
128
+ decodedToken: {authKind: "better-auth", id: "u1"},
129
+ encodedToken: "session-token",
130
+ });
131
+ const outcome = await revalidateSocketSession(socket, {});
132
+ expect(outcome).toBe("invalid-session");
133
+ });
134
+
135
+ it("returns disabled when the reloaded full user has disabled: true", async () => {
136
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "u1"}});
137
+ const outcome = await revalidateSocketSession(socket, {
138
+ userModel: fakeUserModel({u1: {_id: "u1", disabled: true}}),
139
+ });
140
+ expect(outcome).toBe("disabled");
141
+ });
142
+
143
+ it("returns invalid-session when the user no longer exists", async () => {
144
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "gone"}});
145
+ const outcome = await revalidateSocketSession(socket, {userModel: fakeUserModel({})});
146
+ expect(outcome).toBe("invalid-session");
147
+ });
148
+
149
+ it("refreshes socket.data.fullUser on success (D2)", async () => {
150
+ const user = {_id: "u1", disabled: false, organizationIds: ["org-a"]};
151
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "u1"}});
152
+ const outcome = await revalidateSocketSession(socket, {userModel: fakeUserModel({u1: user})});
153
+ expect(outcome).toBe("valid");
154
+ expect(socket.data?.fullUser).toEqual(user);
155
+ });
156
+
157
+ it("returns valid when no userModel is configured (no disabled check possible)", async () => {
158
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "u1"}});
159
+ const outcome = await revalidateSocketSession(socket, {});
160
+ expect(outcome).toBe("valid");
161
+ });
162
+ });
163
+
164
+ describe("reresolveSyncRoomsForSocket (D4)", () => {
165
+ afterEach(() => {
166
+ clearSyncRegistry();
167
+ });
168
+
169
+ it("leaves a room for a tenant the user no longer belongs to and joins a newly granted one", async () => {
170
+ registerSync({
171
+ config: {scope: {field: "organizationId", type: "tenant"}},
172
+ model: RevalTenantModel,
173
+ options: {permissions: {create: [], delete: [], list: [], read: [], update: []}} as any,
174
+ routePath: "/projects",
175
+ });
176
+
177
+ const subscriptions = new Map<string, Set<string>>([
178
+ ["projects", new Set(["sync:projects|tenant:org-old"])],
179
+ ]);
180
+ const socket = makeSocket({
181
+ data: {fullUser: {id: "u1"}, syncSubscriptions: subscriptions},
182
+ decodedToken: {authKind: "jwt", id: "u1"},
183
+ });
184
+
185
+ await reresolveSyncRoomsForSocket(socket, {
186
+ sync: {getUserScopes: () => ["org-new"]},
187
+ });
188
+
189
+ expect(socket.leave).toHaveBeenCalledWith("sync:projects|tenant:org-old");
190
+ expect(socket.join).toHaveBeenCalledWith("sync:projects|tenant:org-new");
191
+ expect(subscriptions.get("projects")).toEqual(new Set(["sync:projects|tenant:org-new"]));
192
+ });
193
+
194
+ it("does nothing when the socket has no sync subscriptions", async () => {
195
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "u1"}});
196
+ await reresolveSyncRoomsForSocket(socket, {});
197
+ expect(socket.leave).not.toHaveBeenCalled();
198
+ expect(socket.join).not.toHaveBeenCalled();
199
+ });
200
+
201
+ it("leaves all rooms when getUserScopes returns no memberships (full revocation)", async () => {
202
+ registerSync({
203
+ config: {scope: {field: "organizationId", type: "tenant"}},
204
+ model: RevalTenantModel,
205
+ options: {permissions: {create: [], delete: [], list: [], read: [], update: []}} as any,
206
+ routePath: "/projects",
207
+ });
208
+ const subscriptions = new Map<string, Set<string>>([
209
+ ["projects", new Set(["sync:projects|tenant:org-a"])],
210
+ ]);
211
+ const socket = makeSocket({
212
+ data: {fullUser: {id: "u1"}, syncSubscriptions: subscriptions},
213
+ decodedToken: {authKind: "jwt", id: "u1"},
214
+ });
215
+
216
+ await reresolveSyncRoomsForSocket(socket, {sync: {getUserScopes: () => []}});
217
+
218
+ expect(socket.leave).toHaveBeenCalledWith("sync:projects|tenant:org-a");
219
+ expect(socket.join).not.toHaveBeenCalled();
220
+ expect(subscriptions.get("projects")).toEqual(new Set());
221
+ });
222
+
223
+ it("keeps an owner-scoped room untouched (always the socket's own userId)", async () => {
224
+ registerSync({
225
+ config: {scope: {type: "owner"}},
226
+ model: RevalOwnerModel,
227
+ options: {permissions: {create: [], delete: [], list: [], read: [], update: []}} as any,
228
+ routePath: "/todos",
229
+ });
230
+ const subscriptions = new Map<string, Set<string>>([
231
+ ["todos", new Set(["sync:todos|owner:u1"])],
232
+ ]);
233
+ const socket = makeSocket({
234
+ data: {fullUser: {id: "u1"}, syncSubscriptions: subscriptions},
235
+ decodedToken: {authKind: "jwt", id: "u1"},
236
+ });
237
+
238
+ await reresolveSyncRoomsForSocket(socket, {});
239
+
240
+ expect(socket.leave).not.toHaveBeenCalled();
241
+ expect(socket.join).not.toHaveBeenCalled();
242
+ });
243
+ });
244
+
245
+ describe("runSessionRevalidationSweep", () => {
246
+ it("disconnects an expired socket, emitting sync:auth-expired first", async () => {
247
+ const socket = makeSocket({
248
+ decodedToken: {
249
+ authKind: "jwt",
250
+ exp: DateTime.now().minus({minutes: 1}).toSeconds(),
251
+ id: "u1",
252
+ },
253
+ });
254
+ const io = {sockets: {sockets: new Map([["socket-1", socket]])}} as any;
255
+
256
+ await runSessionRevalidationSweep(io, {});
257
+
258
+ expect(socket.emit).toHaveBeenCalledWith("sync:auth-expired", {reason: "expired"});
259
+ expect(socket.disconnect).toHaveBeenCalledWith(true);
260
+ });
261
+
262
+ it("disconnects a disabled user's socket", async () => {
263
+ const socket = makeSocket({decodedToken: {authKind: "jwt", id: "u1"}});
264
+ const io = {sockets: {sockets: new Map([["socket-1", socket]])}} as any;
265
+
266
+ await runSessionRevalidationSweep(io, {
267
+ userModel: fakeUserModel({u1: {_id: "u1", disabled: true}}),
268
+ });
269
+
270
+ expect(socket.emit).toHaveBeenCalledWith("sync:auth-expired", {reason: "disabled"});
271
+ expect(socket.disconnect).toHaveBeenCalledWith(true);
272
+ });
273
+
274
+ it("leaves a valid socket connected and does not emit sync:auth-expired", async () => {
275
+ const socket = makeSocket({
276
+ decodedToken: {
277
+ authKind: "jwt",
278
+ exp: DateTime.now().plus({minutes: 10}).toSeconds(),
279
+ id: "u1",
280
+ },
281
+ });
282
+ const io = {sockets: {sockets: new Map([["socket-1", socket]])}} as any;
283
+
284
+ await runSessionRevalidationSweep(io, {});
285
+
286
+ expect(socket.emit).not.toHaveBeenCalled();
287
+ expect(socket.disconnect).not.toHaveBeenCalled();
288
+ });
289
+
290
+ it("continues sweeping other sockets when one throws", async () => {
291
+ const throwing = makeSocket({
292
+ decodedToken: {authKind: "jwt", id: "throws"},
293
+ id: "socket-throws",
294
+ });
295
+ const expired = makeSocket({
296
+ decodedToken: {
297
+ authKind: "jwt",
298
+ exp: DateTime.now().minus({minutes: 1}).toSeconds(),
299
+ id: "u2",
300
+ },
301
+ id: "socket-expired",
302
+ });
303
+ const throwingUserModel = {
304
+ find: async () => {
305
+ throw new Error("db unavailable");
306
+ },
307
+ };
308
+ const io = {
309
+ sockets: {
310
+ sockets: new Map([
311
+ ["socket-throws", throwing],
312
+ ["socket-expired", expired],
313
+ ]),
314
+ },
315
+ } as any;
316
+
317
+ await runSessionRevalidationSweep(io, {userModel: throwingUserModel as any});
318
+
319
+ // The throwing socket's error is caught and logged; it is left connected rather
320
+ // than disconnected on an ambiguous internal failure.
321
+ expect(throwing.disconnect).not.toHaveBeenCalled();
322
+ expect(expired.disconnect).toHaveBeenCalledWith(true);
323
+ });
324
+ });
325
+
326
+ describe("startSessionRevalidationSweep", () => {
327
+ it("does not arm a timer when intervalMs is 0", () => {
328
+ const io = {sockets: {sockets: new Map()}} as any;
329
+ const handle = startSessionRevalidationSweep(io, {intervalMs: 0});
330
+ // No assertion beyond "does not throw" is possible without reaching into timer
331
+ // internals; stop() must be a safe no-op either way.
332
+ expect(() => handle.stop()).not.toThrow();
333
+ });
334
+
335
+ it("returns a handle whose stop() clears the interval", () => {
336
+ const io = {sockets: {sockets: new Map()}} as any;
337
+ const handle = startSessionRevalidationSweep(io, {intervalMs: 60_000});
338
+ expect(() => handle.stop()).not.toThrow();
339
+ // Calling stop() twice must also be safe.
340
+ expect(() => handle.stop()).not.toThrow();
341
+ });
342
+
343
+ it("resolves an options thunk fresh on every tick (no staleness from a captured snapshot)", async () => {
344
+ // Regression for the same staleness bug fixed for the JWT issuer thunk: a
345
+ // static options object captured once at RealtimeApp.onServerCreated() time
346
+ // would use whatever `sync.getUserScopes` was published at that instant,
347
+ // even if SyncApp registers (or its options change) afterwards.
348
+ registerSync({
349
+ config: {scope: {field: "organizationId", type: "tenant"}},
350
+ model: RevalTenantModel,
351
+ options: {permissions: {create: [], delete: [], list: [], read: [], update: []}} as any,
352
+ routePath: "/projects",
353
+ });
354
+ const user = {_id: "u1", disabled: false};
355
+ let scopesAtLastTick: string[] = [];
356
+ const socket = makeSocket({
357
+ data: {
358
+ fullUser: user,
359
+ syncSubscriptions: new Map([["projects", new Set(["sync:projects|tenant:org-v1"])]]),
360
+ },
361
+ decodedToken: {authKind: "jwt", id: "u1"},
362
+ });
363
+ const io = {sockets: {sockets: new Map([["socket-1", socket]])}} as any;
364
+ let currentScopes = ["org-v1"];
365
+
366
+ const handle = startSessionRevalidationSweep(io, () => ({
367
+ intervalMs: 20,
368
+ sync: {
369
+ getUserScopes: () => {
370
+ scopesAtLastTick = currentScopes;
371
+ return currentScopes;
372
+ },
373
+ },
374
+ userModel: fakeUserModel({u1: user}),
375
+ }));
376
+
377
+ await settleFor(60);
378
+ expect(scopesAtLastTick).toEqual(["org-v1"]);
379
+
380
+ currentScopes = ["org-v2"];
381
+ await settleFor(60);
382
+ expect(scopesAtLastTick).toEqual(["org-v2"]);
383
+
384
+ handle.stop();
385
+ clearSyncRegistry();
386
+ });
387
+ });
388
+
389
+ const settleFor = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
390
+
391
+ describe("loadFullUserForSocket (D2)", () => {
392
+ it("populates socket.data.fullUser from the decoded token's id", async () => {
393
+ const user = {_id: "u1", organizationIds: ["org-a"]};
394
+ const socket: any = {data: {}, decodedToken: {id: "u1"}, id: "socket-1"};
395
+
396
+ await loadFullUserForSocket(socket, fakeUserModel({u1: user}));
397
+
398
+ expect(socket.data.fullUser).toEqual(user);
399
+ });
400
+
401
+ it("is a no-op when no userModel is configured", async () => {
402
+ const socket: any = {data: {}, decodedToken: {id: "u1"}, id: "socket-1"};
403
+ await loadFullUserForSocket(socket, undefined);
404
+ expect(socket.data.fullUser).toBeUndefined();
405
+ });
406
+
407
+ it("is a no-op when the decoded token has no id", async () => {
408
+ const socket: any = {data: {}, decodedToken: {}, id: "socket-1"};
409
+ await loadFullUserForSocket(socket, fakeUserModel({u1: {_id: "u1"}}));
410
+ expect(socket.data.fullUser).toBeUndefined();
411
+ });
412
+
413
+ it("swallows a lookup error and leaves fullUser unset", async () => {
414
+ const throwingModel = {
415
+ find: async () => {
416
+ throw new Error("db down");
417
+ },
418
+ };
419
+ const socket: any = {data: {}, decodedToken: {id: "u1"}, id: "socket-1"};
420
+ await loadFullUserForSocket(socket, throwingModel as any);
421
+ expect(socket.data.fullUser).toBeUndefined();
422
+ });
423
+ });
@@ -0,0 +1,273 @@
1
+ import {DateTime} from "luxon";
2
+ import type {Server, Socket} from "socket.io";
3
+
4
+ import type {UserModel} from "../auth";
5
+ import {logger} from "../logger";
6
+ import {findOneOrNoneFor} from "../plugins";
7
+ import {findSyncEntryByCollectionTag} from "../sync/registry";
8
+ import type {SyncAppOptions} from "../sync/routes";
9
+ import {syncRoomForStream} from "../sync/socketHandlers";
10
+ import {streamForScopeValue} from "../sync/streams";
11
+ import type {BetterAuthSocketOptions} from "./socketAuth";
12
+ import {getSocketUser, type SocketDataBag, type SocketWithDecodedToken} from "./socketUser";
13
+
14
+ /**
15
+ * Default interval for the periodic socket session re-validation sweep (D1): 60
16
+ * seconds. Sockets authenticate once at handshake; without a sweep, a revoked
17
+ * session, an expired token, or a user subsequently disabled keeps streaming deltas
18
+ * (including PHI) indefinitely.
19
+ */
20
+ export const DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = 60_000;
21
+
22
+ /** Minimal socket shape the sweep needs. Lets tests drive it with a mock. */
23
+ export interface RevalidatableSocket extends SocketWithDecodedToken {
24
+ id: string;
25
+ encodedToken?: string;
26
+ data?: SocketDataBag;
27
+ emit: (event: string, payload?: unknown) => void;
28
+ disconnect: (close?: boolean) => void;
29
+ join: (room: string) => Promise<void> | void;
30
+ leave: (room: string) => Promise<void> | void;
31
+ }
32
+
33
+ export interface SessionRevalidationOptions {
34
+ /** Application user model, for reloading the full user and its `disabled` flag. */
35
+ userModel?: UserModel;
36
+ /** Enables re-validating Better Auth-authenticated sockets. */
37
+ betterAuth?: BetterAuthSocketOptions;
38
+ /** Active SyncAppOptions (for `getUserScopes`), used by D4's room re-resolution. */
39
+ sync?: SyncAppOptions;
40
+ logInfo?: (message: string) => void;
41
+ }
42
+
43
+ /** Result of re-validating a single socket, for tests/observability. */
44
+ export type RevalidationOutcome = "valid" | "expired" | "disabled" | "invalid-session";
45
+
46
+ /**
47
+ * Re-run the cheap parts of the auth validator for an already-connected socket:
48
+ * - JWT sockets (`decodedToken.authKind === "jwt"`): verify `exp` locally (no
49
+ * signature re-check — a stolen-but-still-valid token is not this sweep's job;
50
+ * revocation-by-expiry and disablement are).
51
+ * - Better Auth sockets (`decodedToken.authKind === "better-auth"`): re-run
52
+ * `auth.api.getSession` for the retained session token.
53
+ * Also reloads the user's `disabled` flag (and the full user document, refreshing
54
+ * `socket.data.fullUser` for D2) when a `userModel` is configured.
55
+ */
56
+ export const revalidateSocketSession = async (
57
+ socket: RevalidatableSocket,
58
+ options: SessionRevalidationOptions
59
+ ): Promise<RevalidationOutcome> => {
60
+ const {authKind, id: userId, exp} = socket.decodedToken ?? {};
61
+
62
+ if (authKind === "jwt") {
63
+ if (typeof exp === "number" && exp <= DateTime.now().toSeconds()) {
64
+ return "expired";
65
+ }
66
+ } else if (authKind === "better-auth") {
67
+ if (!options.betterAuth || !socket.encodedToken) {
68
+ return "invalid-session";
69
+ }
70
+ const session = await options.betterAuth.auth.api.getSession({
71
+ headers: {authorization: `Bearer ${socket.encodedToken}`} as Record<string, string>,
72
+ });
73
+ if (!session?.user?.id) {
74
+ return "invalid-session";
75
+ }
76
+ }
77
+
78
+ if (options.userModel && userId) {
79
+ const fullUser = await findOneOrNoneFor(options.userModel, {_id: userId});
80
+ if (!fullUser) {
81
+ return "invalid-session";
82
+ }
83
+ if ((fullUser as unknown as {disabled?: boolean}).disabled === true) {
84
+ return "disabled";
85
+ }
86
+ // D2: refresh the cached full user so subsequent authorization checks (and the
87
+ // next sweep tick's stream re-resolution below) see current fields — e.g. a
88
+ // membership change to `organizationIds` takes effect without a reconnect.
89
+ if (socket.data) {
90
+ socket.data.fullUser = fullUser;
91
+ }
92
+ }
93
+
94
+ return "valid";
95
+ };
96
+
97
+ /**
98
+ * D4: re-resolve the streams the socket's user currently belongs to for every
99
+ * subscribed collection, and `socket.leave()` any previously-joined sync room the
100
+ * user no longer holds (e.g. a revoked organization membership). Joins any newly
101
+ * granted rooms too, mirroring what a fresh `sync:subscribe` would do, so a
102
+ * membership grant also takes effect without a reconnect.
103
+ */
104
+ export const reresolveSyncRoomsForSocket = async (
105
+ socket: RevalidatableSocket,
106
+ options: SessionRevalidationOptions
107
+ ): Promise<void> => {
108
+ const subscriptions = socket.data?.syncSubscriptions;
109
+ if (!subscriptions || subscriptions.size === 0) {
110
+ return;
111
+ }
112
+ const user = getSocketUser(socket);
113
+ if (!user) {
114
+ return;
115
+ }
116
+
117
+ for (const [collection, currentRooms] of subscriptions) {
118
+ const entry = findSyncEntryByCollectionTag(collection);
119
+ if (!entry) {
120
+ continue;
121
+ }
122
+ const {scope} = entry.config;
123
+ let streams: string[];
124
+ if (typeof scope !== "function" && scope.type === "broadcast") {
125
+ streams = [streamForScopeValue({collectionTag: collection, scope, scopeValue: null})];
126
+ } else if (typeof scope !== "function" && scope.type === "owner") {
127
+ streams = [streamForScopeValue({collectionTag: collection, scope, scopeValue: user.id})];
128
+ } else if (options.sync?.getUserScopes) {
129
+ let scopeValues: string[];
130
+ try {
131
+ scopeValues = await options.sync.getUserScopes(user, entry);
132
+ } catch (error: unknown) {
133
+ logger.error(`[realtime] getUserScopes threw during session revalidation: ${error}`);
134
+ continue;
135
+ }
136
+ streams = scopeValues.map((scopeValue) =>
137
+ streamForScopeValue({collectionTag: collection, scope, scopeValue})
138
+ );
139
+ } else {
140
+ continue;
141
+ }
142
+
143
+ const nextRooms = new Set(streams.map(syncRoomForStream));
144
+ for (const room of currentRooms) {
145
+ if (!nextRooms.has(room)) {
146
+ await socket.leave(room);
147
+ }
148
+ }
149
+ for (const room of nextRooms) {
150
+ if (!currentRooms.has(room)) {
151
+ await socket.join(room);
152
+ }
153
+ }
154
+ subscriptions.set(collection, nextRooms);
155
+ }
156
+ };
157
+
158
+ /**
159
+ * Run one sweep pass over every connected socket: re-validate the session (D1),
160
+ * disconnecting (`sync:auth-expired` then `disconnect(true)`) any socket that fails,
161
+ * and re-resolve sync room membership (D4) for sockets that remain valid.
162
+ */
163
+ export const runSessionRevalidationSweep = async (
164
+ io: Server,
165
+ options: SessionRevalidationOptions = {}
166
+ ): Promise<void> => {
167
+ const logInfo = options.logInfo ?? ((): void => {});
168
+ const sockets = [...io.sockets.sockets.values()] as unknown as RevalidatableSocket[];
169
+
170
+ await Promise.all(
171
+ sockets.map(async (socket) => {
172
+ try {
173
+ const outcome = await revalidateSocketSession(socket, options);
174
+ if (outcome !== "valid") {
175
+ logInfo(
176
+ `[realtime] Session revalidation sweep disconnecting socket ${socket.id}: ${outcome}`
177
+ );
178
+ socket.emit("sync:auth-expired", {reason: outcome});
179
+ socket.disconnect(true);
180
+ return;
181
+ }
182
+ await reresolveSyncRoomsForSocket(socket, options);
183
+ } catch (error: unknown) {
184
+ logger.error(
185
+ `[realtime] Session revalidation sweep failed for socket ${socket.id}: ${error}`
186
+ );
187
+ }
188
+ })
189
+ );
190
+ };
191
+
192
+ /** Handle returned by {@link startSessionRevalidationSweep}; call to stop the timer. */
193
+ export type SessionRevalidationHandle = {stop: () => void};
194
+
195
+ /**
196
+ * Start the periodic sweep (D1). Returns a handle to stop it (called from
197
+ * `RealtimeApp.close()`). A `intervalMs` of 0 disables the sweep (useful for tests
198
+ * that don't want a background timer).
199
+ *
200
+ * `options` may be a plain object or a thunk resolved fresh on EVERY tick — pass a
201
+ * thunk when any field (notably `sync`, whose `getUserScopes` resolver is published
202
+ * by the `SyncApp` plugin and may not be registered yet, or may change, at the time
203
+ * `RealtimeApp.onServerCreated()` runs) must never go stale for the lifetime of the
204
+ * sweep, mirroring the per-handshake freshness `createLegacyJwtValidator`'s issuer
205
+ * thunk already provides.
206
+ */
207
+ export const startSessionRevalidationSweep = (
208
+ io: Server,
209
+ optionsOrThunk:
210
+ | (SessionRevalidationOptions & {intervalMs?: number})
211
+ | (() => SessionRevalidationOptions & {intervalMs?: number}) = {}
212
+ ): SessionRevalidationHandle => {
213
+ const resolveOptions = (): SessionRevalidationOptions & {intervalMs?: number} =>
214
+ typeof optionsOrThunk === "function" ? optionsOrThunk() : optionsOrThunk;
215
+ const intervalMs = resolveOptions().intervalMs ?? DEFAULT_SESSION_REVALIDATION_INTERVAL_MS;
216
+ if (intervalMs <= 0) {
217
+ return {stop: (): void => {}};
218
+ }
219
+ const timer = setInterval(() => {
220
+ void runSessionRevalidationSweep(io, resolveOptions()).catch((error: unknown) => {
221
+ logger.error(`[realtime] Session revalidation sweep tick failed: ${error}`);
222
+ });
223
+ }, intervalMs);
224
+ return {
225
+ stop: (): void => {
226
+ clearInterval(timer);
227
+ },
228
+ };
229
+ };
230
+
231
+ /**
232
+ * Load the full user document for a just-authenticated socket and cache it on
233
+ * `socket.data.fullUser` (D2). Called once at handshake, right after the auth
234
+ * middleware succeeds; the periodic sweep (D1) refreshes it afterwards. A no-op when
235
+ * no `userModel` is configured (falls back to the synthetic decoded-token shape via
236
+ * `getSocketUser`) or the decoded token carries no id (should not happen for a
237
+ * socket that passed auth, but guarded defensively).
238
+ */
239
+ export const loadFullUserForSocket = (
240
+ socket: Socket & {data: SocketDataBag},
241
+ userModel?: UserModel
242
+ ): Promise<void> => {
243
+ const load = loadFullUserIntoSocketData(socket, userModel);
244
+ // Task 9.21: publish the in-flight load so the sync handlers can await it. An event that
245
+ // arrived inside the handshake window would otherwise be authorized against the synthetic
246
+ // JWT-claim user — no `organizationIds`, so a tenant `sync:subscribe` resolved to no
247
+ // streams and the client sat connected but never received data.
248
+ if (socket.data) {
249
+ socket.data.fullUserLoad = load;
250
+ }
251
+ return load;
252
+ };
253
+
254
+ /** The actual load; separated so {@link loadFullUserForSocket} can publish the promise. */
255
+ const loadFullUserIntoSocketData = async (
256
+ socket: Socket & {data: SocketDataBag},
257
+ userModel?: UserModel
258
+ ): Promise<void> => {
259
+ const userId = (socket as unknown as SocketWithDecodedToken).decodedToken?.id;
260
+ if (!userModel || !userId) {
261
+ return;
262
+ }
263
+ try {
264
+ const fullUser = await findOneOrNoneFor(userModel, {_id: userId});
265
+ if (fullUser) {
266
+ socket.data.fullUser = fullUser;
267
+ }
268
+ } catch (error: unknown) {
269
+ logger.error(
270
+ `[realtime] Failed to load full user at handshake for socket ${socket.id}: ${error}`
271
+ );
272
+ }
273
+ };