@terreno/api 0.31.0 → 56.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) 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 +121 -26
  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 +47 -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 +83 -27
  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 +54 -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 +899 -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/api.errors.test.ts +32 -23
  66. package/src/api.test.ts +12 -0
  67. package/src/api.ts +87 -296
  68. package/src/auth.test.ts +202 -0
  69. package/src/auth.ts +134 -23
  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/configuration.test.ts +59 -38
  74. package/src/configurationPlugin.test.ts +72 -42
  75. package/src/docLoader.ts +3 -1
  76. package/src/errors.ts +33 -0
  77. package/src/expressServer.test.ts +7 -1
  78. package/src/index.ts +42 -0
  79. package/src/middleware.test.ts +56 -1
  80. package/src/middleware.ts +15 -0
  81. package/src/openApiCompat.ts +99 -45
  82. package/src/permissions.test.ts +101 -17
  83. package/src/permissions.ts +49 -0
  84. package/src/plugins.test.ts +64 -0
  85. package/src/plugins.ts +56 -0
  86. package/src/realtime/changeStreamWatcher.ts +552 -114
  87. package/src/realtime/realtime.test.ts +157 -0
  88. package/src/realtime/realtimeApp.ts +82 -14
  89. package/src/realtime/realtimeAppSetup.test.ts +25 -27
  90. package/src/realtime/sessionRevalidation.test.ts +423 -0
  91. package/src/realtime/sessionRevalidation.ts +273 -0
  92. package/src/realtime/socketAuth.test.ts +355 -0
  93. package/src/realtime/socketAuth.ts +228 -0
  94. package/src/realtime/socketUser.ts +69 -0
  95. package/src/realtime/types.ts +54 -0
  96. package/src/secretProviders.test.ts +7 -1
  97. package/src/secretProviders.ts +15 -3
  98. package/src/secretProvidersGcpClient.test.ts +66 -0
  99. package/src/sync/ensureSyncIndexes.test.ts +144 -0
  100. package/src/sync/executors.test.ts +882 -0
  101. package/src/sync/executors.ts +705 -0
  102. package/src/sync/integration.test.ts +1160 -0
  103. package/src/sync/loadHarness.ts +618 -0
  104. package/src/sync/models.ts +641 -0
  105. package/src/sync/mutationHandler.test.ts +1252 -0
  106. package/src/sync/mutationHandler.ts +850 -0
  107. package/src/sync/registry.ts +232 -0
  108. package/src/sync/routes.ts +812 -0
  109. package/src/sync/scripts/compactTombstones.test.ts +249 -0
  110. package/src/sync/scripts/compactTombstones.ts +145 -0
  111. package/src/sync/serialize.ts +48 -0
  112. package/src/sync/sessionRevalidationIntegration.test.ts +281 -0
  113. package/src/sync/socketHandlers.ts +320 -0
  114. package/src/sync/streams.ts +188 -0
  115. package/src/sync/sync.test.ts +582 -0
  116. package/src/sync/syncApp.ts +44 -0
  117. package/src/sync/syncBatch.ts +219 -0
  118. package/src/sync/syncFrontier.test.ts +494 -0
  119. package/src/sync/syncPhaseC.test.ts +718 -0
  120. package/src/sync/syncRoutes.test.ts +865 -0
  121. package/src/sync/syncSeqPlugin.ts +730 -0
  122. package/src/sync/syncSocket.test.ts +1440 -0
  123. package/src/sync/types.ts +270 -0
  124. package/src/terrenoApp.ts +37 -17
  125. package/src/tests/bunSetup.ts +8 -0
  126. package/tsconfig.json +4 -4
  127. package/tsconfig.typedoc.json +7 -1
  128. package/dist/__tests__/openApiCompat.test.js +0 -317
  129. package/dist/__tests__/versionCheckPlugin.test.d.ts +0 -1
  130. package/dist/__tests__/versionCheckPlugin.test.js +0 -597
  131. package/dist/actions.openApi.test.d.ts +0 -1
  132. package/dist/actions.openApi.test.js +0 -253
  133. package/dist/actions.test.d.ts +0 -1
  134. package/dist/actions.test.js +0 -1087
  135. package/dist/api.arrayOperations.test.d.ts +0 -1
  136. package/dist/api.arrayOperations.test.js +0 -878
  137. package/dist/api.asyncHandler.test.d.ts +0 -1
  138. package/dist/api.asyncHandler.test.js +0 -236
  139. package/dist/api.coverage.test.d.ts +0 -1
  140. package/dist/api.coverage.test.js +0 -192
  141. package/dist/api.errorPaths.test.d.ts +0 -1
  142. package/dist/api.errorPaths.test.js +0 -887
  143. package/dist/api.errors.test.d.ts +0 -1
  144. package/dist/api.errors.test.js +0 -185
  145. package/dist/api.hooks.test.d.ts +0 -1
  146. package/dist/api.hooks.test.js +0 -950
  147. package/dist/api.query.test.d.ts +0 -1
  148. package/dist/api.query.test.js +0 -948
  149. package/dist/api.test.d.ts +0 -1
  150. package/dist/api.test.js +0 -2820
  151. package/dist/auth.compile.test.d.ts +0 -1
  152. package/dist/auth.compile.test.js +0 -201
  153. package/dist/auth.coverage.test.d.ts +0 -1
  154. package/dist/auth.coverage.test.js +0 -202
  155. package/dist/auth.test.d.ts +0 -1
  156. package/dist/auth.test.js +0 -2286
  157. package/dist/betterAuth.test.d.ts +0 -1
  158. package/dist/betterAuth.test.js +0 -181
  159. package/dist/betterAuthApp.test.d.ts +0 -1
  160. package/dist/betterAuthApp.test.js +0 -242
  161. package/dist/betterAuthSetup.test.d.ts +0 -1
  162. package/dist/betterAuthSetup.test.js +0 -762
  163. package/dist/config.test.d.ts +0 -1
  164. package/dist/config.test.js +0 -353
  165. package/dist/configuration.test.d.ts +0 -1
  166. package/dist/configuration.test.js +0 -980
  167. package/dist/configurationPlugin.test.d.ts +0 -1
  168. package/dist/configurationPlugin.test.js +0 -827
  169. package/dist/consentApp.test.d.ts +0 -1
  170. package/dist/consentApp.test.js +0 -1411
  171. package/dist/docLoader.test.d.ts +0 -1
  172. package/dist/docLoader.test.js +0 -137
  173. package/dist/envConfigurationPlugin.test.d.ts +0 -1
  174. package/dist/envConfigurationPlugin.test.js +0 -369
  175. package/dist/errors.test.d.ts +0 -1
  176. package/dist/errors.test.js +0 -607
  177. package/dist/expressServer.test.d.ts +0 -1
  178. package/dist/expressServer.test.js +0 -1249
  179. package/dist/githubAuth.test.d.ts +0 -1
  180. package/dist/githubAuth.test.js +0 -1142
  181. package/dist/httpClient.test.d.ts +0 -1
  182. package/dist/httpClient.test.js +0 -1471
  183. package/dist/logger.test.d.ts +0 -1
  184. package/dist/logger.test.js +0 -685
  185. package/dist/middleware.test.d.ts +0 -1
  186. package/dist/middleware.test.js +0 -241
  187. package/dist/notifiers/googleChatNotifier.test.d.ts +0 -1
  188. package/dist/notifiers/googleChatNotifier.test.js +0 -298
  189. package/dist/notifiers/slackNotifier.test.d.ts +0 -1
  190. package/dist/notifiers/slackNotifier.test.js +0 -297
  191. package/dist/notifiers/zoomNotifier.test.d.ts +0 -1
  192. package/dist/notifiers/zoomNotifier.test.js +0 -373
  193. package/dist/openApi.test.d.ts +0 -1
  194. package/dist/openApi.test.js +0 -620
  195. package/dist/openApiBuilder.test.d.ts +0 -1
  196. package/dist/openApiBuilder.test.js +0 -599
  197. package/dist/openApiEtag.test.d.ts +0 -1
  198. package/dist/openApiEtag.test.js +0 -86
  199. package/dist/openApiValidator.test.d.ts +0 -1
  200. package/dist/openApiValidator.test.js +0 -795
  201. package/dist/permissions.middleware.test.d.ts +0 -1
  202. package/dist/permissions.middleware.test.js +0 -308
  203. package/dist/permissions.test.d.ts +0 -1
  204. package/dist/permissions.test.js +0 -439
  205. package/dist/plugins.test.d.ts +0 -1
  206. package/dist/plugins.test.js +0 -902
  207. package/dist/populate.test.d.ts +0 -1
  208. package/dist/populate.test.js +0 -370
  209. package/dist/realtime/realtime.test.d.ts +0 -10
  210. package/dist/realtime/realtime.test.js +0 -4213
  211. package/dist/realtime/realtimeAppSetup.test.d.ts +0 -1
  212. package/dist/realtime/realtimeAppSetup.test.js +0 -213
  213. package/dist/requestContext.test.d.ts +0 -1
  214. package/dist/requestContext.test.js +0 -412
  215. package/dist/scriptRunner.test.d.ts +0 -1
  216. package/dist/scriptRunner.test.js +0 -386
  217. package/dist/secretProviders.test.d.ts +0 -1
  218. package/dist/secretProviders.test.js +0 -726
  219. package/dist/syncConsents.test.d.ts +0 -1
  220. package/dist/syncConsents.test.js +0 -522
  221. package/dist/terrenoApp.test.d.ts +0 -1
  222. package/dist/terrenoApp.test.js +0 -489
  223. package/dist/tests/bunSetup.d.ts +0 -1
  224. package/dist/tests/fixtures/compileAuthEntry.d.ts +0 -1
  225. package/dist/tests/fixtures/compileAuthEntry.js +0 -37
  226. package/dist/tests/testEnv.d.ts +0 -0
  227. package/dist/tests/testEnv.js +0 -6
  228. package/dist/transformers.test.d.ts +0 -1
  229. package/dist/transformers.test.js +0 -423
  230. package/dist/utils.test.d.ts +0 -1
  231. package/dist/utils.test.js +0 -242
  232. /package/dist/{__tests__/openApiCompat.test.d.ts → sync/loadHarness.d.ts} +0 -0
@@ -0,0 +1,438 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ var __values = (this && this.__values) || function(o) {
39
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
40
+ if (m) return m.call(o);
41
+ if (o && typeof o.length === "number") return {
42
+ next: function () {
43
+ if (o && i >= o.length) o = void 0;
44
+ return { value: o && o[i++], done: !o };
45
+ }
46
+ };
47
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
48
+ };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
+ if (ar || !(i in from)) {
68
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
+ ar[i] = from[i];
70
+ }
71
+ }
72
+ return to.concat(ar || Array.prototype.slice.call(from));
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.loadFullUserForSocket = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.reresolveSyncRoomsForSocket = exports.revalidateSocketSession = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = void 0;
76
+ var luxon_1 = require("luxon");
77
+ var logger_1 = require("../logger");
78
+ var plugins_1 = require("../plugins");
79
+ var registry_1 = require("../sync/registry");
80
+ var socketHandlers_1 = require("../sync/socketHandlers");
81
+ var streams_1 = require("../sync/streams");
82
+ var socketUser_1 = require("./socketUser");
83
+ /**
84
+ * Default interval for the periodic socket session re-validation sweep (D1): 60
85
+ * seconds. Sockets authenticate once at handshake; without a sweep, a revoked
86
+ * session, an expired token, or a user subsequently disabled keeps streaming deltas
87
+ * (including PHI) indefinitely.
88
+ */
89
+ exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = 60000;
90
+ /**
91
+ * Re-run the cheap parts of the auth validator for an already-connected socket:
92
+ * - JWT sockets (`decodedToken.authKind === "jwt"`): verify `exp` locally (no
93
+ * signature re-check — a stolen-but-still-valid token is not this sweep's job;
94
+ * revocation-by-expiry and disablement are).
95
+ * - Better Auth sockets (`decodedToken.authKind === "better-auth"`): re-run
96
+ * `auth.api.getSession` for the retained session token.
97
+ * Also reloads the user's `disabled` flag (and the full user document, refreshing
98
+ * `socket.data.fullUser` for D2) when a `userModel` is configured.
99
+ */
100
+ var revalidateSocketSession = function (socket, options) { return __awaiter(void 0, void 0, void 0, function () {
101
+ var _a, authKind, userId, exp, session, fullUser;
102
+ var _b, _c;
103
+ return __generator(this, function (_d) {
104
+ switch (_d.label) {
105
+ case 0:
106
+ _a = (_b = socket.decodedToken) !== null && _b !== void 0 ? _b : {}, authKind = _a.authKind, userId = _a.id, exp = _a.exp;
107
+ if (!(authKind === "jwt")) return [3 /*break*/, 1];
108
+ if (typeof exp === "number" && exp <= luxon_1.DateTime.now().toSeconds()) {
109
+ return [2 /*return*/, "expired"];
110
+ }
111
+ return [3 /*break*/, 3];
112
+ case 1:
113
+ if (!(authKind === "better-auth")) return [3 /*break*/, 3];
114
+ if (!options.betterAuth || !socket.encodedToken) {
115
+ return [2 /*return*/, "invalid-session"];
116
+ }
117
+ return [4 /*yield*/, options.betterAuth.auth.api.getSession({
118
+ headers: { authorization: "Bearer ".concat(socket.encodedToken) },
119
+ })];
120
+ case 2:
121
+ session = _d.sent();
122
+ if (!((_c = session === null || session === void 0 ? void 0 : session.user) === null || _c === void 0 ? void 0 : _c.id)) {
123
+ return [2 /*return*/, "invalid-session"];
124
+ }
125
+ _d.label = 3;
126
+ case 3:
127
+ if (!(options.userModel && userId)) return [3 /*break*/, 5];
128
+ return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(options.userModel, { _id: userId })];
129
+ case 4:
130
+ fullUser = _d.sent();
131
+ if (!fullUser) {
132
+ return [2 /*return*/, "invalid-session"];
133
+ }
134
+ if (fullUser.disabled === true) {
135
+ return [2 /*return*/, "disabled"];
136
+ }
137
+ // D2: refresh the cached full user so subsequent authorization checks (and the
138
+ // next sweep tick's stream re-resolution below) see current fields — e.g. a
139
+ // membership change to `organizationIds` takes effect without a reconnect.
140
+ if (socket.data) {
141
+ socket.data.fullUser = fullUser;
142
+ }
143
+ _d.label = 5;
144
+ case 5: return [2 /*return*/, "valid"];
145
+ }
146
+ });
147
+ }); };
148
+ exports.revalidateSocketSession = revalidateSocketSession;
149
+ /**
150
+ * D4: re-resolve the streams the socket's user currently belongs to for every
151
+ * subscribed collection, and `socket.leave()` any previously-joined sync room the
152
+ * user no longer holds (e.g. a revoked organization membership). Joins any newly
153
+ * granted rooms too, mirroring what a fresh `sync:subscribe` would do, so a
154
+ * membership grant also takes effect without a reconnect.
155
+ */
156
+ var reresolveSyncRoomsForSocket = function (socket, options) { return __awaiter(void 0, void 0, void 0, function () {
157
+ var subscriptions, user, _loop_1, subscriptions_1, subscriptions_1_1, _a, collection, currentRooms, e_1_1;
158
+ var e_1, _b;
159
+ var _c, _d;
160
+ return __generator(this, function (_e) {
161
+ switch (_e.label) {
162
+ case 0:
163
+ subscriptions = (_c = socket.data) === null || _c === void 0 ? void 0 : _c.syncSubscriptions;
164
+ if (!subscriptions || subscriptions.size === 0) {
165
+ return [2 /*return*/];
166
+ }
167
+ user = (0, socketUser_1.getSocketUser)(socket);
168
+ if (!user) {
169
+ return [2 /*return*/];
170
+ }
171
+ _loop_1 = function (collection, currentRooms) {
172
+ var entry, scope, streams, scopeValues, error_1, nextRooms, currentRooms_1, currentRooms_1_1, room, e_2_1, nextRooms_1, nextRooms_1_1, room, e_3_1;
173
+ var e_2, _f, e_3, _g;
174
+ return __generator(this, function (_h) {
175
+ switch (_h.label) {
176
+ case 0:
177
+ entry = (0, registry_1.findSyncEntryByCollectionTag)(collection);
178
+ if (!entry) {
179
+ return [2 /*return*/, "continue"];
180
+ }
181
+ scope = entry.config.scope;
182
+ streams = void 0;
183
+ if (!(typeof scope !== "function" && scope.type === "broadcast")) return [3 /*break*/, 1];
184
+ streams = [(0, streams_1.streamForScopeValue)({ collectionTag: collection, scope: scope, scopeValue: null })];
185
+ return [3 /*break*/, 8];
186
+ case 1:
187
+ if (!(typeof scope !== "function" && scope.type === "owner")) return [3 /*break*/, 2];
188
+ streams = [(0, streams_1.streamForScopeValue)({ collectionTag: collection, scope: scope, scopeValue: user.id })];
189
+ return [3 /*break*/, 8];
190
+ case 2:
191
+ if (!((_d = options.sync) === null || _d === void 0 ? void 0 : _d.getUserScopes)) return [3 /*break*/, 7];
192
+ scopeValues = void 0;
193
+ _h.label = 3;
194
+ case 3:
195
+ _h.trys.push([3, 5, , 6]);
196
+ return [4 /*yield*/, options.sync.getUserScopes(user, entry)];
197
+ case 4:
198
+ scopeValues = _h.sent();
199
+ return [3 /*break*/, 6];
200
+ case 5:
201
+ error_1 = _h.sent();
202
+ logger_1.logger.error("[realtime] getUserScopes threw during session revalidation: ".concat(error_1));
203
+ return [2 /*return*/, "continue"];
204
+ case 6:
205
+ streams = scopeValues.map(function (scopeValue) {
206
+ return (0, streams_1.streamForScopeValue)({ collectionTag: collection, scope: scope, scopeValue: scopeValue });
207
+ });
208
+ return [3 /*break*/, 8];
209
+ case 7: return [2 /*return*/, "continue"];
210
+ case 8:
211
+ nextRooms = new Set(streams.map(socketHandlers_1.syncRoomForStream));
212
+ _h.label = 9;
213
+ case 9:
214
+ _h.trys.push([9, 14, 15, 16]);
215
+ currentRooms_1 = (e_2 = void 0, __values(currentRooms)), currentRooms_1_1 = currentRooms_1.next();
216
+ _h.label = 10;
217
+ case 10:
218
+ if (!!currentRooms_1_1.done) return [3 /*break*/, 13];
219
+ room = currentRooms_1_1.value;
220
+ if (!!nextRooms.has(room)) return [3 /*break*/, 12];
221
+ return [4 /*yield*/, socket.leave(room)];
222
+ case 11:
223
+ _h.sent();
224
+ _h.label = 12;
225
+ case 12:
226
+ currentRooms_1_1 = currentRooms_1.next();
227
+ return [3 /*break*/, 10];
228
+ case 13: return [3 /*break*/, 16];
229
+ case 14:
230
+ e_2_1 = _h.sent();
231
+ e_2 = { error: e_2_1 };
232
+ return [3 /*break*/, 16];
233
+ case 15:
234
+ try {
235
+ if (currentRooms_1_1 && !currentRooms_1_1.done && (_f = currentRooms_1.return)) _f.call(currentRooms_1);
236
+ }
237
+ finally { if (e_2) throw e_2.error; }
238
+ return [7 /*endfinally*/];
239
+ case 16:
240
+ _h.trys.push([16, 21, 22, 23]);
241
+ nextRooms_1 = (e_3 = void 0, __values(nextRooms)), nextRooms_1_1 = nextRooms_1.next();
242
+ _h.label = 17;
243
+ case 17:
244
+ if (!!nextRooms_1_1.done) return [3 /*break*/, 20];
245
+ room = nextRooms_1_1.value;
246
+ if (!!currentRooms.has(room)) return [3 /*break*/, 19];
247
+ return [4 /*yield*/, socket.join(room)];
248
+ case 18:
249
+ _h.sent();
250
+ _h.label = 19;
251
+ case 19:
252
+ nextRooms_1_1 = nextRooms_1.next();
253
+ return [3 /*break*/, 17];
254
+ case 20: return [3 /*break*/, 23];
255
+ case 21:
256
+ e_3_1 = _h.sent();
257
+ e_3 = { error: e_3_1 };
258
+ return [3 /*break*/, 23];
259
+ case 22:
260
+ try {
261
+ if (nextRooms_1_1 && !nextRooms_1_1.done && (_g = nextRooms_1.return)) _g.call(nextRooms_1);
262
+ }
263
+ finally { if (e_3) throw e_3.error; }
264
+ return [7 /*endfinally*/];
265
+ case 23:
266
+ subscriptions.set(collection, nextRooms);
267
+ return [2 /*return*/];
268
+ }
269
+ });
270
+ };
271
+ _e.label = 1;
272
+ case 1:
273
+ _e.trys.push([1, 6, 7, 8]);
274
+ subscriptions_1 = __values(subscriptions), subscriptions_1_1 = subscriptions_1.next();
275
+ _e.label = 2;
276
+ case 2:
277
+ if (!!subscriptions_1_1.done) return [3 /*break*/, 5];
278
+ _a = __read(subscriptions_1_1.value, 2), collection = _a[0], currentRooms = _a[1];
279
+ return [5 /*yield**/, _loop_1(collection, currentRooms)];
280
+ case 3:
281
+ _e.sent();
282
+ _e.label = 4;
283
+ case 4:
284
+ subscriptions_1_1 = subscriptions_1.next();
285
+ return [3 /*break*/, 2];
286
+ case 5: return [3 /*break*/, 8];
287
+ case 6:
288
+ e_1_1 = _e.sent();
289
+ e_1 = { error: e_1_1 };
290
+ return [3 /*break*/, 8];
291
+ case 7:
292
+ try {
293
+ if (subscriptions_1_1 && !subscriptions_1_1.done && (_b = subscriptions_1.return)) _b.call(subscriptions_1);
294
+ }
295
+ finally { if (e_1) throw e_1.error; }
296
+ return [7 /*endfinally*/];
297
+ case 8: return [2 /*return*/];
298
+ }
299
+ });
300
+ }); };
301
+ exports.reresolveSyncRoomsForSocket = reresolveSyncRoomsForSocket;
302
+ /**
303
+ * Run one sweep pass over every connected socket: re-validate the session (D1),
304
+ * disconnecting (`sync:auth-expired` then `disconnect(true)`) any socket that fails,
305
+ * and re-resolve sync room membership (D4) for sockets that remain valid.
306
+ */
307
+ var runSessionRevalidationSweep = function (io_1) {
308
+ var args_1 = [];
309
+ for (var _i = 1; _i < arguments.length; _i++) {
310
+ args_1[_i - 1] = arguments[_i];
311
+ }
312
+ return __awaiter(void 0, __spreadArray([io_1], __read(args_1), false), void 0, function (io, options) {
313
+ var logInfo, sockets;
314
+ var _a;
315
+ if (options === void 0) { options = {}; }
316
+ return __generator(this, function (_b) {
317
+ switch (_b.label) {
318
+ case 0:
319
+ logInfo = (_a = options.logInfo) !== null && _a !== void 0 ? _a : (function () { });
320
+ sockets = __spreadArray([], __read(io.sockets.sockets.values()), false);
321
+ return [4 /*yield*/, Promise.all(sockets.map(function (socket) { return __awaiter(void 0, void 0, void 0, function () {
322
+ var outcome, error_2;
323
+ return __generator(this, function (_a) {
324
+ switch (_a.label) {
325
+ case 0:
326
+ _a.trys.push([0, 3, , 4]);
327
+ return [4 /*yield*/, (0, exports.revalidateSocketSession)(socket, options)];
328
+ case 1:
329
+ outcome = _a.sent();
330
+ if (outcome !== "valid") {
331
+ logInfo("[realtime] Session revalidation sweep disconnecting socket ".concat(socket.id, ": ").concat(outcome));
332
+ socket.emit("sync:auth-expired", { reason: outcome });
333
+ socket.disconnect(true);
334
+ return [2 /*return*/];
335
+ }
336
+ return [4 /*yield*/, (0, exports.reresolveSyncRoomsForSocket)(socket, options)];
337
+ case 2:
338
+ _a.sent();
339
+ return [3 /*break*/, 4];
340
+ case 3:
341
+ error_2 = _a.sent();
342
+ logger_1.logger.error("[realtime] Session revalidation sweep failed for socket ".concat(socket.id, ": ").concat(error_2));
343
+ return [3 /*break*/, 4];
344
+ case 4: return [2 /*return*/];
345
+ }
346
+ });
347
+ }); }))];
348
+ case 1:
349
+ _b.sent();
350
+ return [2 /*return*/];
351
+ }
352
+ });
353
+ });
354
+ };
355
+ exports.runSessionRevalidationSweep = runSessionRevalidationSweep;
356
+ /**
357
+ * Start the periodic sweep (D1). Returns a handle to stop it (called from
358
+ * `RealtimeApp.close()`). A `intervalMs` of 0 disables the sweep (useful for tests
359
+ * that don't want a background timer).
360
+ *
361
+ * `options` may be a plain object or a thunk resolved fresh on EVERY tick — pass a
362
+ * thunk when any field (notably `sync`, whose `getUserScopes` resolver is published
363
+ * by the `SyncApp` plugin and may not be registered yet, or may change, at the time
364
+ * `RealtimeApp.onServerCreated()` runs) must never go stale for the lifetime of the
365
+ * sweep, mirroring the per-handshake freshness `createLegacyJwtValidator`'s issuer
366
+ * thunk already provides.
367
+ */
368
+ var startSessionRevalidationSweep = function (io, optionsOrThunk) {
369
+ var _a;
370
+ if (optionsOrThunk === void 0) { optionsOrThunk = {}; }
371
+ var resolveOptions = function () {
372
+ return typeof optionsOrThunk === "function" ? optionsOrThunk() : optionsOrThunk;
373
+ };
374
+ var intervalMs = (_a = resolveOptions().intervalMs) !== null && _a !== void 0 ? _a : exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS;
375
+ if (intervalMs <= 0) {
376
+ return { stop: function () { } };
377
+ }
378
+ var timer = setInterval(function () {
379
+ void (0, exports.runSessionRevalidationSweep)(io, resolveOptions()).catch(function (error) {
380
+ logger_1.logger.error("[realtime] Session revalidation sweep tick failed: ".concat(error));
381
+ });
382
+ }, intervalMs);
383
+ return {
384
+ stop: function () {
385
+ clearInterval(timer);
386
+ },
387
+ };
388
+ };
389
+ exports.startSessionRevalidationSweep = startSessionRevalidationSweep;
390
+ /**
391
+ * Load the full user document for a just-authenticated socket and cache it on
392
+ * `socket.data.fullUser` (D2). Called once at handshake, right after the auth
393
+ * middleware succeeds; the periodic sweep (D1) refreshes it afterwards. A no-op when
394
+ * no `userModel` is configured (falls back to the synthetic decoded-token shape via
395
+ * `getSocketUser`) or the decoded token carries no id (should not happen for a
396
+ * socket that passed auth, but guarded defensively).
397
+ */
398
+ var loadFullUserForSocket = function (socket, userModel) {
399
+ var load = loadFullUserIntoSocketData(socket, userModel);
400
+ // Task 9.21: publish the in-flight load so the sync handlers can await it. An event that
401
+ // arrived inside the handshake window would otherwise be authorized against the synthetic
402
+ // JWT-claim user — no `organizationIds`, so a tenant `sync:subscribe` resolved to no
403
+ // streams and the client sat connected but never received data.
404
+ if (socket.data) {
405
+ socket.data.fullUserLoad = load;
406
+ }
407
+ return load;
408
+ };
409
+ exports.loadFullUserForSocket = loadFullUserForSocket;
410
+ /** The actual load; separated so {@link loadFullUserForSocket} can publish the promise. */
411
+ var loadFullUserIntoSocketData = function (socket, userModel) { return __awaiter(void 0, void 0, void 0, function () {
412
+ var userId, fullUser, error_3;
413
+ var _a;
414
+ return __generator(this, function (_b) {
415
+ switch (_b.label) {
416
+ case 0:
417
+ userId = (_a = socket.decodedToken) === null || _a === void 0 ? void 0 : _a.id;
418
+ if (!userModel || !userId) {
419
+ return [2 /*return*/];
420
+ }
421
+ _b.label = 1;
422
+ case 1:
423
+ _b.trys.push([1, 3, , 4]);
424
+ return [4 /*yield*/, (0, plugins_1.findOneOrNoneFor)(userModel, { _id: userId })];
425
+ case 2:
426
+ fullUser = _b.sent();
427
+ if (fullUser) {
428
+ socket.data.fullUser = fullUser;
429
+ }
430
+ return [3 /*break*/, 4];
431
+ case 3:
432
+ error_3 = _b.sent();
433
+ logger_1.logger.error("[realtime] Failed to load full user at handshake for socket ".concat(socket.id, ": ").concat(error_3));
434
+ return [3 /*break*/, 4];
435
+ case 4: return [2 /*return*/];
436
+ }
437
+ });
438
+ }); };
@@ -0,0 +1,97 @@
1
+ import type { Socket } from "socket.io";
2
+ import type { UserModel } from "../auth";
3
+ import type { BetterAuthInstance } from "../betterAuthSetup";
4
+ import type { SocketWithDecodedToken } from "./socketUser";
5
+ /**
6
+ * Pluggable socket authentication for RealtimeApp.
7
+ *
8
+ * The Socket.io handshake token (`socket.handshake.auth.token`) is validated by a chain of
9
+ * validators tried in order; the first one that succeeds populates `socket.decodedToken`
10
+ * (the shape `getSocketUser` consumes) and the connection proceeds. If every validator
11
+ * fails, the connection is rejected with the last validator's error.
12
+ *
13
+ * Validators:
14
+ * 1. Legacy JWT (default, always first) — the existing `@thream/socketio-jwt` middleware,
15
+ * wrapped unchanged so accepted payloads, secret handling, and error shapes are
16
+ * byte-for-byte identical to the previous hardcoded setup.
17
+ * 2. Better Auth session (optional) — enabled via `RealtimeAppOptions.betterAuth`. The
18
+ * handshake token is validated as a Better Auth session via `auth.api.getSession`
19
+ * (presented as an `Authorization: Bearer` credential, resolved by Better Auth's
20
+ * bearer plugin), and `socket.decodedToken` is populated as `{id, admin,
21
+ * isAnonymous: false}` exactly like the JWT path.
22
+ */
23
+ /** The subset of a Socket.io socket the validators need. Lets tests pass a stub. */
24
+ export interface AuthenticatableSocket extends SocketWithDecodedToken {
25
+ handshake: {
26
+ auth: {
27
+ [key: string]: unknown;
28
+ token?: string;
29
+ };
30
+ };
31
+ encodedToken?: string;
32
+ }
33
+ /**
34
+ * A socket auth validator: resolve after populating `socket.decodedToken`, or reject to
35
+ * let the next validator in the chain try.
36
+ */
37
+ export type SocketAuthValidator = (socket: AuthenticatableSocket) => Promise<void>;
38
+ /** Options for the Better Auth session validator. */
39
+ export interface BetterAuthSocketOptions {
40
+ /** The instance returned by `createBetterAuth`. */
41
+ auth: BetterAuthInstance;
42
+ /**
43
+ * Optional application user model. When provided, the Better Auth user is resolved to
44
+ * the app user (via `betterAuthId`) so `decodedToken.id`/`admin` match the identity the
45
+ * REST layer uses. Without it, the Better Auth user id is used and `admin` is false.
46
+ */
47
+ userModel?: UserModel;
48
+ }
49
+ /**
50
+ * Legacy JWT validator: wraps the `@thream/socketio-jwt` middleware so its observable
51
+ * behavior (token format requirements, secret verification, `decodedToken` payload,
52
+ * `UnauthorizedError` shapes) is identical to the previous direct `io.use(authorize(...))`.
53
+ *
54
+ * D1: `@thream/socketio-jwt`'s `authorize()` has no `issuer` option — it only verifies
55
+ * the signature/algorithm — so without this the socket path silently accepted a
56
+ * validly-signed token issued for a DIFFERENT `TOKEN_ISSUER` (e.g. a token from another
57
+ * environment sharing the same `TOKEN_SECRET`), unlike the HTTP path's
58
+ * `jwt.verify(token, secret, {issuer})`. When `issuer` is provided, the post-verify
59
+ * `onAuthentication` hook checks `decodedToken.iss` and rejects a mismatch with the
60
+ * same `UnauthorizedError` shape the signature-verification failure path uses, so
61
+ * callers cannot distinguish "bad signature" from "wrong issuer" from the error alone
62
+ * (matching the non-disclosure posture the HTTP path also has).
63
+ *
64
+ * `issuer` may be a plain string or a thunk (`() => string | undefined`) resolved on
65
+ * EVERY handshake — the HTTP path's `jwt.verify` reads `process.env.TOKEN_ISSUER` fresh
66
+ * per request rather than once at server startup, and a static string captured once at
67
+ * `RealtimeApp.onServerCreated()` time would go stale if `TOKEN_ISSUER` changes later
68
+ * (e.g. test suites that mutate it between fixtures). Pass a thunk to preserve that
69
+ * per-request freshness; a plain string is still supported for callers who intentionally
70
+ * want a fixed value.
71
+ */
72
+ export declare const createLegacyJwtValidator: (tokenSecret: string, issuer?: string | (() => string | undefined)) => SocketAuthValidator;
73
+ /**
74
+ * Better Auth session validator: treats the handshake token as a Better Auth session token
75
+ * and validates it via `auth.api.getSession` (the same lookup the HTTP session middleware
76
+ * uses). The token is presented both as a bearer Authorization header (for the Better Auth
77
+ * bearer plugin) and as the session cookie, so either transport configuration works.
78
+ */
79
+ export declare const createBetterAuthValidator: (options: BetterAuthSocketOptions) => SocketAuthValidator;
80
+ /**
81
+ * Build the Socket.io auth middleware from a validator chain: validators run in order and
82
+ * the first success wins; when all fail the connection is rejected with the last error.
83
+ */
84
+ export declare const createSocketAuthMiddleware: ({ tokenSecret, issuer, betterAuth, extraValidators, }: {
85
+ /** Secret for the legacy JWT validator (same handling as before the refactor). */
86
+ tokenSecret: string;
87
+ /**
88
+ * JWT issuer to require (D1 parity with the HTTP path's `jwt.verify(token, secret,
89
+ * {issuer})`). Omitted means no issuer check, matching pre-D1 behavior. A thunk is
90
+ * resolved fresh on every handshake (see {@link createLegacyJwtValidator}).
91
+ */
92
+ issuer?: string | (() => string | undefined);
93
+ /** Enables the Better Auth session validator after the legacy JWT validator. */
94
+ betterAuth?: BetterAuthSocketOptions;
95
+ /** Additional validators appended to the chain (after JWT and Better Auth). */
96
+ extraValidators?: SocketAuthValidator[];
97
+ }) => ((socket: Socket, next: (error?: Error) => void) => void);