@terreno/api 57.4.0 → 57.6.1

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 (210) hide show
  1. package/README.md +5 -5
  2. package/bunfig.toml +1 -1
  3. package/dist/actions.js +197 -368
  4. package/dist/adminModelRouter.js +88 -173
  5. package/dist/api.js +617 -852
  6. package/dist/audit/auditApp.js +48 -89
  7. package/dist/audit/auditEventModel.js +15 -16
  8. package/dist/audit/cloudTasksEnqueue.js +56 -149
  9. package/dist/audit/diff.js +70 -160
  10. package/dist/audit/processQueue.js +25 -70
  11. package/dist/audit/rbacSink.js +25 -66
  12. package/dist/audit/record.js +129 -251
  13. package/dist/auth.js +432 -681
  14. package/dist/authRecovery.js +155 -269
  15. package/dist/authTokens.js +43 -118
  16. package/dist/betterAuthApp.js +25 -26
  17. package/dist/betterAuthSetup.js +258 -413
  18. package/dist/browserLogsRoute.d.ts +6 -0
  19. package/dist/browserLogsRoute.js +97 -0
  20. package/dist/collectionRegistry.js +32 -47
  21. package/dist/config.js +53 -122
  22. package/dist/configurationApp.js +180 -361
  23. package/dist/configurationPlugin.js +130 -302
  24. package/dist/consentApp.js +276 -421
  25. package/dist/docLoader.js +78 -126
  26. package/dist/envConfigurationPlugin.js +25 -147
  27. package/dist/errors.js +151 -247
  28. package/dist/example.js +28 -34
  29. package/dist/expressServer.d.ts +10 -0
  30. package/dist/expressServer.js +109 -255
  31. package/dist/frameworkModelNames.d.ts +24 -0
  32. package/dist/frameworkModelNames.js +31 -0
  33. package/dist/githubAuth.js +152 -216
  34. package/dist/httpClient.js +176 -264
  35. package/dist/index.d.ts +2 -0
  36. package/dist/index.js +7 -2
  37. package/dist/logger.js +145 -278
  38. package/dist/mcp/auth.js +76 -128
  39. package/dist/mcp/createMCPRequest.js +4 -5
  40. package/dist/mcp/handlers.js +268 -480
  41. package/dist/mcp/query.js +56 -150
  42. package/dist/mcp/registry.js +17 -30
  43. package/dist/mcp/schemaGenerator.js +95 -181
  44. package/dist/mcp/server.js +28 -100
  45. package/dist/mcp/serviceTokens.js +102 -191
  46. package/dist/mcp/toolGenerator.js +78 -191
  47. package/dist/middleware.js +15 -27
  48. package/dist/migrations/fixtures/all-down/20260910120000-one.js +2 -42
  49. package/dist/migrations/fixtures/all-down/20260910120001-two.js +2 -42
  50. package/dist/migrations/fixtures/bad-id/20260910120000-mismatch.js +1 -39
  51. package/dist/migrations/fixtures/bad-name/not-a-migration.js +1 -39
  52. package/dist/migrations/fixtures/valid/20260910120000-alpha.js +1 -39
  53. package/dist/migrations/fixtures/valid/20260910120001-beta.js +2 -42
  54. package/dist/migrations/generate.js +107 -229
  55. package/dist/migrations/load.js +75 -201
  56. package/dist/migrations/lock.js +54 -126
  57. package/dist/migrations/runner.js +192 -446
  58. package/dist/migrations/schemaCatalog.js +122 -263
  59. package/dist/models/consentForm.js +6 -6
  60. package/dist/models/consentResponse.js +5 -5
  61. package/dist/models/mcpServiceToken.js +66 -156
  62. package/dist/models/notification.js +6 -6
  63. package/dist/models/notificationPreference.js +6 -6
  64. package/dist/models/versionConfig.js +5 -5
  65. package/dist/notifications/notificationService.js +133 -273
  66. package/dist/notifications/notificationsApp.js +85 -179
  67. package/dist/notifications/notificationsBeforeSend.js +19 -64
  68. package/dist/notifiers/googleChatNotifier.js +36 -117
  69. package/dist/notifiers/slackNotifier.d.ts +31 -2
  70. package/dist/notifiers/slackNotifier.js +170 -119
  71. package/dist/notifiers/zoomNotifier.js +60 -111
  72. package/dist/openApi.js +107 -122
  73. package/dist/openApiBuilder.js +117 -159
  74. package/dist/openApiCompat.js +81 -148
  75. package/dist/openApiEtag.js +7 -7
  76. package/dist/openApiValidator.js +177 -286
  77. package/dist/orgs/orgContext.js +87 -157
  78. package/dist/orgs/orgPermissions.js +29 -68
  79. package/dist/orgs/orgPlugin.js +9 -27
  80. package/dist/orgs/organizationModel.js +65 -166
  81. package/dist/orgs/organizationSettings.js +29 -36
  82. package/dist/orgs/orgsApp.js +346 -608
  83. package/dist/permissions.js +88 -181
  84. package/dist/plugins.js +125 -218
  85. package/dist/populate.js +130 -240
  86. package/dist/rateLimit/applyTrustProxy.js +1 -1
  87. package/dist/rateLimit/createStore.js +7 -8
  88. package/dist/rateLimit/memoryStore.js +22 -100
  89. package/dist/rateLimit/middleware.js +48 -99
  90. package/dist/rateLimit/mongoStore.js +54 -112
  91. package/dist/rateLimit/policies.js +41 -75
  92. package/dist/rateLimit/redisStore.js +39 -133
  93. package/dist/rbac/access.js +119 -267
  94. package/dist/rbac/assertAllowed.js +95 -171
  95. package/dist/rbac/auditModel.js +14 -58
  96. package/dist/rbac/backfillAdmins.js +24 -130
  97. package/dist/rbac/fieldViews.js +46 -141
  98. package/dist/rbac/membershipOrgAdminSource.js +28 -99
  99. package/dist/rbac/middleware.js +30 -96
  100. package/dist/rbac/modelRouterAccess.js +130 -307
  101. package/dist/rbac/permissionUtils.js +40 -179
  102. package/dist/rbac/realtimeAccess.js +81 -147
  103. package/dist/rbac/resolve.d.ts +1 -1
  104. package/dist/rbac/resolve.js +148 -342
  105. package/dist/rbac/roleManager.js +318 -700
  106. package/dist/rbac/roleModel.js +44 -171
  107. package/dist/rbac/routes.js +93 -196
  108. package/dist/rbac/scopes.js +39 -133
  109. package/dist/rbac/statements.js +23 -91
  110. package/dist/rbac/userPlugin.js +3 -29
  111. package/dist/realtime/changeStreamWatcher.js +489 -800
  112. package/dist/realtime/deprecation.js +8 -10
  113. package/dist/realtime/queryMatcher.js +110 -191
  114. package/dist/realtime/queryStore.js +35 -118
  115. package/dist/realtime/realtimeApp.js +247 -401
  116. package/dist/realtime/registry.js +19 -30
  117. package/dist/realtime/sessionRevalidation.js +132 -358
  118. package/dist/realtime/socketAuth.js +89 -208
  119. package/dist/realtime/socketUser.js +10 -56
  120. package/dist/requestContext.js +93 -139
  121. package/dist/schemaMetadata.js +179 -274
  122. package/dist/scriptRunner.js +96 -266
  123. package/dist/scrubAdminFields.js +36 -108
  124. package/dist/secretProviders.js +130 -299
  125. package/dist/seedRunner.js +221 -514
  126. package/dist/sync/adminBroadcastScope.js +58 -170
  127. package/dist/sync/adminWindowAccess.js +15 -86
  128. package/dist/sync/adminWindowMutation.js +110 -181
  129. package/dist/sync/executors.js +425 -629
  130. package/dist/sync/loadHarness.js +392 -689
  131. package/dist/sync/models.js +181 -341
  132. package/dist/sync/mutationHandler.js +533 -801
  133. package/dist/sync/registrationSideEffects.js +41 -95
  134. package/dist/sync/registry.js +29 -49
  135. package/dist/sync/routes.js +484 -817
  136. package/dist/sync/scripts/compactTombstones.js +83 -228
  137. package/dist/sync/serialize.js +18 -58
  138. package/dist/sync/socketHandlers.js +253 -478
  139. package/dist/sync/streams.js +49 -117
  140. package/dist/sync/syncApp.js +12 -15
  141. package/dist/sync/syncBatch.js +63 -168
  142. package/dist/sync/syncSeqPlugin.js +430 -702
  143. package/dist/syncConsents.js +113 -253
  144. package/dist/terrenoApp.js +166 -276
  145. package/dist/tests/createTestData.js +146 -256
  146. package/dist/tests/models.js +14 -54
  147. package/dist/tests/mongoTestSetup.js +42 -103
  148. package/dist/tests/testHelper.js +31 -93
  149. package/dist/tests.js +12 -51
  150. package/dist/transformers.js +61 -164
  151. package/dist/utils.js +31 -93
  152. package/dist/vendor/wesleytodd-openapi/index.js +37 -51
  153. package/dist/vendor/wesleytodd-openapi/lib/generate-doc.js +32 -40
  154. package/dist/vendor/wesleytodd-openapi/lib/layer-schema.js +3 -3
  155. package/dist/vendor/wesleytodd-openapi/lib/ui.js +50 -19
  156. package/dist/vendor/wesleytodd-openapi/lib/validate.js +19 -47
  157. package/dist/versionCheckPlugin.js +52 -100
  158. package/dist/webhooks/headerValue.js +2 -2
  159. package/dist/webhooks/idempotency/memoryStore.js +16 -59
  160. package/dist/webhooks/idempotency/mongoStore.js +55 -130
  161. package/dist/webhooks/idempotency/webhookReceipt.js +9 -9
  162. package/dist/webhooks/rawBody.js +1 -1
  163. package/dist/webhooks/timingSafeEqual.js +4 -5
  164. package/dist/webhooks/verifiers/hmac.js +17 -18
  165. package/dist/webhooks/verifiers/sendgrid.js +20 -22
  166. package/dist/webhooks/verifiers/stripe.js +31 -65
  167. package/dist/webhooks/verifiers/twilio.js +23 -73
  168. package/dist/webhooks/webhooksApp.js +78 -177
  169. package/dist/zodOpenApi.js +2 -2
  170. package/package.json +6 -6
  171. package/src/__tests__/browserLogsRoute.test.ts +165 -0
  172. package/src/api.arrayOperations.test.ts +44 -0
  173. package/src/api.ts +64 -39
  174. package/src/audit/auditApp.test.ts +5 -5
  175. package/src/audit/auditEventModel.ts +7 -3
  176. package/src/audit/auditRouter.test.ts +5 -5
  177. package/src/audit/rbacSink.test.ts +2 -2
  178. package/src/audit/record.test.ts +2 -2
  179. package/src/audit/record.ts +3 -2
  180. package/src/auth.ts +1 -1
  181. package/src/authRecovery.test.ts +43 -0
  182. package/src/authRecovery.ts +16 -10
  183. package/src/authTokens.ts +6 -2
  184. package/src/authVerification.test.ts +22 -0
  185. package/src/browserLogsRoute.ts +110 -0
  186. package/src/configurationPlugin.test.ts +1 -11
  187. package/src/expressServer.ts +10 -0
  188. package/src/frameworkModelNames.test.ts +62 -0
  189. package/src/frameworkModelNames.ts +33 -0
  190. package/src/index.ts +7 -0
  191. package/src/isolated/migrateCliConnect.isolated.ts +51 -0
  192. package/src/mcp/auth.test.ts +34 -1
  193. package/src/migrations/cli.test.ts +0 -23
  194. package/src/models/mcpServiceToken.ts +4 -3
  195. package/src/models/notification.ts +3 -2
  196. package/src/models/notificationPreference.ts +1 -1
  197. package/src/notifications/notificationsApp.test.ts +24 -1
  198. package/src/notifiers/slackNotifier.test.ts +186 -1
  199. package/src/notifiers/slackNotifier.ts +167 -8
  200. package/src/orgs/orgPlugin.ts +1 -1
  201. package/src/orgs/organizationModel.ts +11 -6
  202. package/src/plugins.test.ts +5 -0
  203. package/src/plugins.ts +3 -0
  204. package/src/realtime/realtimeApp.ts +1 -1
  205. package/src/sync/integration.test.ts +2 -2
  206. package/src/terrenoApp.ts +3 -0
  207. package/src/types.d.ts +1 -0
  208. package/src/webhooks/idempotency/webhookReceipt.ts +4 -3
  209. package/tsconfig.json +13 -54
  210. package/tsconfig.typedoc.json +2 -0
@@ -1,28 +1,16 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
2
  Object.defineProperty(exports, "__esModule", { value: true });
14
3
  exports.clearRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.getRealtimeRegistry = exports.updateRealtimeRegistryOptions = exports.registerRealtime = void 0;
15
- var collectionRegistry_1 = require("../collectionRegistry");
16
- var toRealtimeEntry = function (record) { return ({
4
+ const collectionRegistry_1 = require("../collectionRegistry");
5
+ const toRealtimeEntry = (record) => ({
17
6
  collectionName: record.model.collection.collectionName,
18
7
  config: record.options.realtime,
19
8
  modelName: record.model.modelName,
20
9
  options: record.options,
21
10
  routePath: record.routePath,
22
- }); };
23
- var realtimeModelForEntry = function (entry) {
24
- var _a;
25
- var registered = (_a = (0, collectionRegistry_1.listCollections)().find(function (record) { return record.routePath === entry.routePath; })) === null || _a === void 0 ? void 0 : _a.model;
11
+ });
12
+ const realtimeModelForEntry = (entry) => {
13
+ const registered = (0, collectionRegistry_1.listCollections)().find((record) => record.routePath === entry.routePath)?.model;
26
14
  if (registered) {
27
15
  return registered;
28
16
  }
@@ -31,33 +19,34 @@ var realtimeModelForEntry = function (entry) {
31
19
  modelName: entry.modelName,
32
20
  };
33
21
  };
34
- var registerRealtime = function (entry) {
22
+ const registerRealtime = (entry) => {
35
23
  (0, collectionRegistry_1.registerCollection)({
36
24
  model: realtimeModelForEntry(entry),
37
- options: __assign(__assign({}, entry.options), { realtime: entry.config }),
25
+ options: {
26
+ ...entry.options,
27
+ realtime: entry.config,
28
+ },
38
29
  routePath: entry.routePath,
39
30
  });
40
31
  };
41
32
  exports.registerRealtime = registerRealtime;
42
- var updateRealtimeRegistryOptions = function (routePath, options) {
33
+ const updateRealtimeRegistryOptions = (routePath, options) => {
43
34
  (0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
44
35
  };
45
36
  exports.updateRealtimeRegistryOptions = updateRealtimeRegistryOptions;
46
- var getRealtimeRegistry = function () {
47
- return (0, collectionRegistry_1.listCollections)()
48
- .filter(function (record) { return record.surfaces.realtime; })
49
- .map(toRealtimeEntry);
50
- };
37
+ const getRealtimeRegistry = () => (0, collectionRegistry_1.listCollections)()
38
+ .filter((record) => record.surfaces.realtime)
39
+ .map(toRealtimeEntry);
51
40
  exports.getRealtimeRegistry = getRealtimeRegistry;
52
- var findRegistryEntryByCollection = function (collectionName) {
53
- return (0, exports.getRealtimeRegistry)().find(function (entry) { return entry.collectionName === collectionName; });
41
+ const findRegistryEntryByCollection = (collectionName) => {
42
+ return (0, exports.getRealtimeRegistry)().find((entry) => entry.collectionName === collectionName);
54
43
  };
55
44
  exports.findRegistryEntryByCollection = findRegistryEntryByCollection;
56
- var findRegistryEntryByRoutePath = function (collection) {
57
- return (0, exports.getRealtimeRegistry)().find(function (entry) { return entry.routePath === "/".concat(collection) || entry.routePath === collection; });
45
+ const findRegistryEntryByRoutePath = (collection) => {
46
+ return (0, exports.getRealtimeRegistry)().find((entry) => entry.routePath === `/${collection}` || entry.routePath === collection);
58
47
  };
59
48
  exports.findRegistryEntryByRoutePath = findRegistryEntryByRoutePath;
60
- var clearRealtimeRegistry = function () {
49
+ const clearRealtimeRegistry = () => {
61
50
  (0, collectionRegistry_1.clearCollectionRegistry)();
62
51
  };
63
52
  exports.clearRealtimeRegistry = clearRealtimeRegistry;
@@ -1,92 +1,20 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
75
3
  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");
4
+ const luxon_1 = require("luxon");
5
+ const logger_1 = require("../logger");
6
+ const plugins_1 = require("../plugins");
7
+ const registry_1 = require("../sync/registry");
8
+ const socketHandlers_1 = require("../sync/socketHandlers");
9
+ const streams_1 = require("../sync/streams");
10
+ const socketUser_1 = require("./socketUser");
83
11
  /**
84
12
  * Default interval for the periodic socket session re-validation sweep (D1): 60
85
13
  * seconds. Sockets authenticate once at handshake; without a sweep, a revoked
86
14
  * session, an expired token, or a user subsequently disabled keeps streaming deltas
87
15
  * (including PHI) indefinitely.
88
16
  */
89
- exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = 60000;
17
+ exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = 60_000;
90
18
  /**
91
19
  * Re-run the cheap parts of the auth validator for an already-connected socket:
92
20
  * - JWT sockets (`decodedToken.authKind === "jwt"`): verify `exp` locally (no
@@ -97,54 +25,41 @@ exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = 60000;
97
25
  * Also reloads the user's `disabled` flag (and the full user document, refreshing
98
26
  * `socket.data.fullUser` for D2) when a `userModel` is configured.
99
27
  */
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"];
28
+ const revalidateSocketSession = async (socket, options) => {
29
+ const { authKind, id: userId, exp } = socket.decodedToken ?? {};
30
+ if (authKind === "jwt") {
31
+ if (typeof exp === "number" && exp <= luxon_1.DateTime.now().toSeconds()) {
32
+ return "expired";
33
+ }
34
+ }
35
+ else if (authKind === "better-auth") {
36
+ if (!options.betterAuth || !socket.encodedToken) {
37
+ return "invalid-session";
38
+ }
39
+ const session = await options.betterAuth.auth.api.getSession({
40
+ headers: { authorization: `Bearer ${socket.encodedToken}` },
41
+ });
42
+ if (!session?.user?.id) {
43
+ return "invalid-session";
145
44
  }
146
- });
147
- }); };
45
+ }
46
+ if (options.userModel && userId) {
47
+ const fullUser = await (0, plugins_1.findOneOrNoneFor)(options.userModel, { _id: userId });
48
+ if (!fullUser) {
49
+ return "invalid-session";
50
+ }
51
+ if (fullUser.disabled === true) {
52
+ return "disabled";
53
+ }
54
+ // D2: refresh the cached full user so subsequent authorization checks (and the
55
+ // next sweep tick's stream re-resolution below) see current fields — e.g. a
56
+ // membership change to `organizationIds` takes effect without a reconnect.
57
+ if (socket.data) {
58
+ socket.data.fullUser = fullUser;
59
+ }
60
+ }
61
+ return "valid";
62
+ };
148
63
  exports.revalidateSocketSession = revalidateSocketSession;
149
64
  /**
150
65
  * D4: re-resolve the streams the socket's user currently belongs to for every
@@ -153,204 +68,80 @@ exports.revalidateSocketSession = revalidateSocketSession;
153
68
  * granted rooms too, mirroring what a fresh `sync:subscribe` would do, so a
154
69
  * membership grant also takes effect without a reconnect.
155
70
  */
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*/];
71
+ const reresolveSyncRoomsForSocket = async (socket, options) => {
72
+ const subscriptions = socket.data?.syncSubscriptions;
73
+ if (!subscriptions || subscriptions.size === 0) {
74
+ return;
75
+ }
76
+ const user = (0, socketUser_1.getSocketUser)(socket);
77
+ if (!user) {
78
+ return;
79
+ }
80
+ for (const [collection, currentRooms] of subscriptions) {
81
+ const entry = (0, registry_1.findSyncEntryByCollectionTag)(collection);
82
+ if (!entry) {
83
+ continue;
84
+ }
85
+ const { scope } = entry.config;
86
+ let streams;
87
+ if (typeof scope !== "function" && scope.type === "broadcast") {
88
+ streams = [(0, streams_1.streamForScopeValue)({ collectionTag: collection, scope, scopeValue: null })];
89
+ }
90
+ else if (typeof scope !== "function" && scope.type === "owner") {
91
+ streams = [(0, streams_1.streamForScopeValue)({ collectionTag: collection, scope, scopeValue: user.id })];
92
+ }
93
+ else if (options.sync?.getUserScopes) {
94
+ let scopeValues;
95
+ try {
96
+ scopeValues = await options.sync.getUserScopes(user, entry);
97
+ }
98
+ catch (error) {
99
+ logger_1.logger.error(`[realtime] getUserScopes threw during session revalidation: ${error}`);
100
+ continue;
101
+ }
102
+ streams = scopeValues.map((scopeValue) => (0, streams_1.streamForScopeValue)({ collectionTag: collection, scope, scopeValue }));
298
103
  }
299
- });
300
- }); };
104
+ else {
105
+ continue;
106
+ }
107
+ const nextRooms = new Set(streams.map(socketHandlers_1.syncRoomForStream));
108
+ for (const room of currentRooms) {
109
+ if (!nextRooms.has(room)) {
110
+ await socket.leave(room);
111
+ }
112
+ }
113
+ for (const room of nextRooms) {
114
+ if (!currentRooms.has(room)) {
115
+ await socket.join(room);
116
+ }
117
+ }
118
+ subscriptions.set(collection, nextRooms);
119
+ }
120
+ };
301
121
  exports.reresolveSyncRoomsForSocket = reresolveSyncRoomsForSocket;
302
122
  /**
303
123
  * Run one sweep pass over every connected socket: re-validate the session (D1),
304
124
  * disconnecting (`sync:auth-expired` then `disconnect(true)`) any socket that fails,
305
125
  * and re-resolve sync room membership (D4) for sockets that remain valid.
306
126
  */
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*/];
127
+ const runSessionRevalidationSweep = async (io, options = {}) => {
128
+ const logInfo = options.logInfo ?? (() => { });
129
+ const sockets = [...io.sockets.sockets.values()];
130
+ await Promise.all(sockets.map(async (socket) => {
131
+ try {
132
+ const outcome = await (0, exports.revalidateSocketSession)(socket, options);
133
+ if (outcome !== "valid") {
134
+ logInfo(`[realtime] Session revalidation sweep disconnecting socket ${socket.id}: ${outcome}`);
135
+ socket.emit("sync:auth-expired", { reason: outcome });
136
+ socket.disconnect(true);
137
+ return;
351
138
  }
352
- });
353
- });
139
+ await (0, exports.reresolveSyncRoomsForSocket)(socket, options);
140
+ }
141
+ catch (error) {
142
+ logger_1.logger.error(`[realtime] Session revalidation sweep failed for socket ${socket.id}: ${error}`);
143
+ }
144
+ }));
354
145
  };
355
146
  exports.runSessionRevalidationSweep = runSessionRevalidationSweep;
356
147
  /**
@@ -365,23 +156,19 @@ exports.runSessionRevalidationSweep = runSessionRevalidationSweep;
365
156
  * sweep, mirroring the per-handshake freshness `createLegacyJwtValidator`'s issuer
366
157
  * thunk already provides.
367
158
  */
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;
159
+ const startSessionRevalidationSweep = (io, optionsOrThunk = {}) => {
160
+ const resolveOptions = () => typeof optionsOrThunk === "function" ? optionsOrThunk() : optionsOrThunk;
161
+ const intervalMs = resolveOptions().intervalMs ?? exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS;
375
162
  if (intervalMs <= 0) {
376
- return { stop: function () { } };
163
+ return { stop: () => { } };
377
164
  }
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));
165
+ const timer = setInterval(() => {
166
+ void (0, exports.runSessionRevalidationSweep)(io, resolveOptions()).catch((error) => {
167
+ logger_1.logger.error(`[realtime] Session revalidation sweep tick failed: ${error}`);
381
168
  });
382
169
  }, intervalMs);
383
170
  return {
384
- stop: function () {
171
+ stop: () => {
385
172
  clearInterval(timer);
386
173
  },
387
174
  };
@@ -395,8 +182,8 @@ exports.startSessionRevalidationSweep = startSessionRevalidationSweep;
395
182
  * `getSocketUser`) or the decoded token carries no id (should not happen for a
396
183
  * socket that passed auth, but guarded defensively).
397
184
  */
398
- var loadFullUserForSocket = function (socket, userModel) {
399
- var load = loadFullUserIntoSocketData(socket, userModel);
185
+ const loadFullUserForSocket = (socket, userModel) => {
186
+ const load = loadFullUserIntoSocketData(socket, userModel);
400
187
  // Task 9.21: publish the in-flight load so the sync handlers can await it. An event that
401
188
  // arrived inside the handshake window would otherwise be authorized against the synthetic
402
189
  // JWT-claim user — no `organizationIds`, so a tenant `sync:subscribe` resolved to no
@@ -408,31 +195,18 @@ var loadFullUserForSocket = function (socket, userModel) {
408
195
  };
409
196
  exports.loadFullUserForSocket = loadFullUserForSocket;
410
197
  /** 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*/];
198
+ const loadFullUserIntoSocketData = async (socket, userModel) => {
199
+ const userId = socket.decodedToken?.id;
200
+ if (!userModel || !userId) {
201
+ return;
202
+ }
203
+ try {
204
+ const fullUser = await (0, plugins_1.findOneOrNoneFor)(userModel, { _id: userId });
205
+ if (fullUser) {
206
+ socket.data.fullUser = fullUser;
436
207
  }
437
- });
438
- }); };
208
+ }
209
+ catch (error) {
210
+ logger_1.logger.error(`[realtime] Failed to load full user at handshake for socket ${socket.id}: ${error}`);
211
+ }
212
+ };