@terreno/api 57.2.0 → 57.3.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 (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -74,6 +74,7 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
74
74
  Object.defineProperty(exports, "__esModule", { value: true });
75
75
  exports.createPermissionResolver = void 0;
76
76
  var access_1 = require("better-auth/plugins/access");
77
+ var luxon_1 = require("luxon");
77
78
  var logger_1 = require("../logger");
78
79
  var permissionUtils_1 = require("./permissionUtils");
79
80
  var DEFAULT_CACHE_TTL_MS = 30000;
@@ -90,7 +91,7 @@ var createPermissionResolver = function (args) {
90
91
  var sourceCache = new Map();
91
92
  var enforceCacheBound = function () {
92
93
  var e_1, _a;
93
- var now = Date.now();
94
+ var now = luxon_1.DateTime.now().toMillis();
94
95
  try {
95
96
  for (var permissionCache_1 = __values(permissionCache), permissionCache_1_1 = permissionCache_1.next(); !permissionCache_1_1.done; permissionCache_1_1 = permissionCache_1.next()) {
96
97
  var _b = __read(permissionCache_1_1.value, 2), userId = _b[0], entry = _b[1];
@@ -219,7 +220,7 @@ var createPermissionResolver = function (args) {
219
220
  return __generator(this, function (_f) {
220
221
  switch (_f.label) {
221
222
  case 0:
222
- now = Date.now();
223
+ now = luxon_1.DateTime.now().toMillis();
223
224
  cached = (_a = sourceCache.get(user.id)) === null || _a === void 0 ? void 0 : _a.get(source.name);
224
225
  if (!!shouldCache) return [3 /*break*/, 4];
225
226
  _f.label = 1;
@@ -274,7 +275,7 @@ var createPermissionResolver = function (args) {
274
275
  case 0:
275
276
  if (shouldCache) {
276
277
  cached = permissionCache.get(user.id);
277
- if (cached && cached.expiresAt > Date.now()) {
278
+ if (cached && cached.expiresAt > luxon_1.DateTime.now().toMillis()) {
278
279
  rememberPermissions(user.id, cached);
279
280
  return [2 /*return*/, cached.permissions];
280
281
  }
@@ -354,7 +355,7 @@ var createPermissionResolver = function (args) {
354
355
  }
355
356
  if (shouldCache) {
356
357
  rememberPermissions(user.id, {
357
- expiresAt: Date.now() + cacheTtlMs,
358
+ expiresAt: luxon_1.DateTime.now().plus({ milliseconds: cacheTtlMs }).toMillis(),
358
359
  permissions: permissions,
359
360
  });
360
361
  }
@@ -44,6 +44,12 @@ var express_1 = __importDefault(require("express"));
44
44
  var api_1 = require("../api");
45
45
  var auth_1 = require("../auth");
46
46
  var errors_1 = require("../errors");
47
+ var pathParam = function (value, title) {
48
+ if (typeof value !== "string" || value.length === 0) {
49
+ throw new errors_1.APIError({ status: 400, title: title });
50
+ }
51
+ return value;
52
+ };
47
53
  var rbacRouter = function (_a) {
48
54
  var access = _a.access, userModel = _a.userModel, _b = _a.basePath, basePath = _b === void 0 ? "/rbac" : _b;
49
55
  return {
@@ -97,7 +103,7 @@ var rbacRouter = function (_a) {
97
103
  return [4 /*yield*/, access.roles.update({
98
104
  actor: actor,
99
105
  changes: req.body,
100
- roleName: req.params.name,
106
+ roleName: pathParam(req.params.name, "Role name is required"),
101
107
  })];
102
108
  case 1:
103
109
  role = _a.sent();
@@ -114,7 +120,10 @@ var rbacRouter = function (_a) {
114
120
  if (!actor) {
115
121
  throw new errors_1.APIError({ status: 401, title: "Unauthorized" });
116
122
  }
117
- return [4 /*yield*/, access.roles.remove({ actor: actor, roleName: req.params.name })];
123
+ return [4 /*yield*/, access.roles.remove({
124
+ actor: actor,
125
+ roleName: pathParam(req.params.name, "Role name is required"),
126
+ })];
118
127
  case 1:
119
128
  _a.sent();
120
129
  return [2 /*return*/, res.status(204).send()];
@@ -127,7 +136,7 @@ var rbacRouter = function (_a) {
127
136
  switch (_a.label) {
128
137
  case 0: return [4 /*yield*/, access.roles.previewRoleChange({
129
138
  permissions: req.body.permissions,
130
- roleName: req.params.name,
139
+ roleName: pathParam(req.params.name, "Role name is required"),
131
140
  })];
132
141
  case 1:
133
142
  diff = _a.sent();
@@ -140,7 +149,7 @@ var rbacRouter = function (_a) {
140
149
  var _a;
141
150
  return __generator(this, function (_b) {
142
151
  switch (_b.label) {
143
- case 0: return [4 /*yield*/, userModel.findById(req.params.id)];
152
+ case 0: return [4 /*yield*/, userModel.findById(pathParam(req.params.id, "User id is required"))];
144
153
  case 1:
145
154
  user = _b.sent();
146
155
  if (!user) {
@@ -176,7 +185,7 @@ var rbacRouter = function (_a) {
176
185
  return [4 /*yield*/, access.roles.assign({
177
186
  actor: actor,
178
187
  roleNames: req.body.roleNames,
179
- userId: req.params.id,
188
+ userId: pathParam(req.params.id, "User id is required"),
180
189
  })];
181
190
  case 1:
182
191
  _a.sent();
@@ -196,7 +205,7 @@ var rbacRouter = function (_a) {
196
205
  return [4 /*yield*/, access.roles.previewAssignment({
197
206
  actor: actor,
198
207
  roleNames: req.body.roleNames,
199
- userId: req.params.id,
208
+ userId: pathParam(req.params.id, "User id is required"),
200
209
  })];
201
210
  case 1:
202
211
  diff = _a.sent();
@@ -0,0 +1,12 @@
1
+ /**
2
+ * One-line warning for modelRouter `realtime`. Keep in sync with the
3
+ * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
4
+ */
5
+ export declare const REALTIME_DEPRECATION_MESSAGE = "modelRouter `realtime` is deprecated and will be removed in Terreno 58. Use `sync` with `@terreno/syncdb` instead. See docs/how-to/migrate-rtk-to-syncdb.md. RealtimeApp remains required for sync sockets.";
6
+ /**
7
+ * Emits a one-time deprecation warning per model/routePath per process when a
8
+ * consumer enables the legacy RTK cache-patching `realtime` option.
9
+ */
10
+ export declare const warnRealtimeDeprecated: (modelName: string, routePath?: string) => void;
11
+ /** @internal Test helper — clears one-time realtime deprecation warnings. */
12
+ export declare const resetRealtimeDeprecationWarningsForTests: () => void;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resetRealtimeDeprecationWarningsForTests = exports.warnRealtimeDeprecated = exports.REALTIME_DEPRECATION_MESSAGE = void 0;
4
+ var logger_1 = require("../logger");
5
+ /**
6
+ * One-line warning for modelRouter `realtime`. Keep in sync with the
7
+ * `@terreno/rtk` helpers and `docs/implementationPlans/remove-legacy-realtime.md`.
8
+ */
9
+ exports.REALTIME_DEPRECATION_MESSAGE = "modelRouter `realtime` is deprecated and will be removed in Terreno 58. Use `sync` with `@terreno/syncdb` instead. See docs/how-to/migrate-rtk-to-syncdb.md. RealtimeApp remains required for sync sockets.";
10
+ var warnedKeys = new Set();
11
+ var warningKey = function (modelName, routePath) {
12
+ return "".concat(modelName, ":").concat(routePath !== null && routePath !== void 0 ? routePath : "");
13
+ };
14
+ /**
15
+ * Emits a one-time deprecation warning per model/routePath per process when a
16
+ * consumer enables the legacy RTK cache-patching `realtime` option.
17
+ */
18
+ var warnRealtimeDeprecated = function (modelName, routePath) {
19
+ var key = warningKey(modelName, routePath);
20
+ if (warnedKeys.has(key)) {
21
+ return;
22
+ }
23
+ warnedKeys.add(key);
24
+ var location = routePath ? "".concat(modelName, " at ").concat(routePath) : modelName;
25
+ logger_1.logger.warn("[realtime] ".concat(exports.REALTIME_DEPRECATION_MESSAGE, " (").concat(location, ")"));
26
+ };
27
+ exports.warnRealtimeDeprecated = warnRealtimeDeprecated;
28
+ /** @internal Test helper — clears one-time realtime deprecation warnings. */
29
+ var resetRealtimeDeprecationWarningsForTests = function () {
30
+ warnedKeys.clear();
31
+ };
32
+ exports.resetRealtimeDeprecationWarningsForTests = resetRealtimeDeprecationWarningsForTests;
@@ -48,7 +48,7 @@ export declare const installRealtimeSocketHandlers: (socket: RealtimeSocketLike,
48
48
  * TerrenoPlugin that provides real-time sync via Socket.io and MongoDB change streams.
49
49
  *
50
50
  * Attaches a Socket.io server to the HTTP server created by TerrenoApp.start(),
51
- * sets up JWT authentication for socket connections, manages room subscriptions
51
+ * sets up JWT and/or Better Auth authentication for socket connections, manages room subscriptions
52
52
  * (model, document, and query rooms), and starts a change stream watcher that
53
53
  * emits events to connected clients.
54
54
  *
@@ -401,7 +401,7 @@ exports.installRealtimeSocketHandlers = installRealtimeSocketHandlers;
401
401
  * TerrenoPlugin that provides real-time sync via Socket.io and MongoDB change streams.
402
402
  *
403
403
  * Attaches a Socket.io server to the HTTP server created by TerrenoApp.start(),
404
- * sets up JWT authentication for socket connections, manages room subscriptions
404
+ * sets up JWT and/or Better Auth authentication for socket connections, manages room subscriptions
405
405
  * (model, document, and query rooms), and starts a change stream watcher that
406
406
  * emits events to connected clients.
407
407
  *
@@ -469,13 +469,13 @@ var RealtimeApp = /** @class */ (function () {
469
469
  origin: "*",
470
470
  },
471
471
  });
472
- // Authentication middleware: legacy JWT first, optionally Better Auth sessions.
472
+ // Authentication middleware: legacy JWT first when configured, optionally Better Auth sessions.
473
473
  var tokenSecret = (_d = this.config.tokenSecret) !== null && _d !== void 0 ? _d : process.env.TOKEN_SECRET;
474
- if (!tokenSecret) {
474
+ if (!tokenSecret && !this.config.betterAuth) {
475
475
  throw new errors_1.APIError({
476
476
  status: 500,
477
- title: "[realtime] TOKEN_SECRET is required for socket authentication. " +
478
- "Set process.env.TOKEN_SECRET or pass tokenSecret in RealtimeAppOptions.",
477
+ title: "[realtime] Socket authentication requires TOKEN_SECRET or Better Auth. " +
478
+ "Set process.env.TOKEN_SECRET, pass tokenSecret, or configure betterAuth.",
479
479
  });
480
480
  }
481
481
  // D1: pass the issuer through for parity with the HTTP JWT path
@@ -485,12 +485,11 @@ var RealtimeApp = /** @class */ (function () {
485
485
  // process.env.TOKEN_ISSUER — or to an explicitly configured tokenIssuer — is
486
486
  // honored on every handshake, matching the HTTP path's per-request env read.
487
487
  var resolveTokenIssuer = function () { var _a; return (_a = _this.config.tokenIssuer) !== null && _a !== void 0 ? _a : process.env.TOKEN_ISSUER; };
488
- this.io.use((0, socketAuth_1.createSocketAuthMiddleware)({
489
- betterAuth: this.config.betterAuth,
490
- issuer: resolveTokenIssuer,
491
- tokenSecret: tokenSecret,
492
- }));
493
- logInfo("[realtime] Socket auth middleware added (JWT".concat(this.config.betterAuth ? " + Better Auth" : "", ")"));
488
+ this.io.use((0, socketAuth_1.createSocketAuthMiddleware)(__assign({ betterAuth: this.config.betterAuth, issuer: resolveTokenIssuer }, (tokenSecret ? { tokenSecret: tokenSecret } : {}))));
489
+ var authKinds = [tokenSecret ? "JWT" : null, this.config.betterAuth ? "Better Auth" : null]
490
+ .filter(Boolean)
491
+ .join(" + ");
492
+ logInfo("[realtime] Socket auth middleware added (".concat(authKinds, ")"));
494
493
  // Task 9.21: tenant/custom sync scopes can only be resolved from the full user
495
494
  // document, so warn loudly here (once, at startup) rather than silently serving
496
495
  // empty tenant streams for the life of the process.
@@ -1,46 +1,15 @@
1
1
  import type { ModelRouterOptions } from "../api";
2
2
  import type { RealtimeConfig } from "./types";
3
- /**
4
- * A registered model with real-time sync configuration.
5
- */
6
3
  export interface RealtimeRegistryEntry {
7
- /** Mongoose model name (e.g. "Todo") */
8
4
  modelName: string;
9
- /** Route path (e.g. "/todos") */
10
5
  routePath: string;
11
- /** Collection name in MongoDB (e.g. "todos") */
12
6
  collectionName: string;
13
- /** Real-time configuration from modelRouter options */
14
7
  config: RealtimeConfig;
15
- /**
16
- * Full modelRouter options (for responseHandler, permissions, etc.), erased to
17
- * `unknown` since the registry holds entries for every model.
18
- */
19
8
  options: ModelRouterOptions<unknown>;
20
9
  }
21
- /**
22
- * Register a model for real-time sync. Called automatically by modelRouter
23
- * when the `realtime` option is provided.
24
- */
25
10
  export declare const registerRealtime: (entry: RealtimeRegistryEntry) => void;
26
- /**
27
- * Replace options on an existing registry entry (e.g. after TerrenoApp injects accessControl).
28
- * Matches by routePath; no-op if the route was never registered.
29
- */
30
11
  export declare const updateRealtimeRegistryOptions: (routePath: string, options: ModelRouterOptions<unknown>) => void;
31
- /**
32
- * Get all registered real-time models.
33
- */
34
12
  export declare const getRealtimeRegistry: () => RealtimeRegistryEntry[];
35
- /**
36
- * Find a registry entry by MongoDB collection name.
37
- */
38
13
  export declare const findRegistryEntryByCollection: (collectionName: string) => RealtimeRegistryEntry | undefined;
39
- /**
40
- * Find a registry entry by route path / collection tag (e.g. "todos").
41
- */
42
14
  export declare const findRegistryEntryByRoutePath: (collection: string) => RealtimeRegistryEntry | undefined;
43
- /**
44
- * Clear the registry (for testing).
45
- */
46
15
  export declare const clearRealtimeRegistry: () => void;
@@ -1,50 +1,63 @@
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
+ };
2
13
  Object.defineProperty(exports, "__esModule", { value: true });
3
14
  exports.clearRealtimeRegistry = exports.findRegistryEntryByRoutePath = exports.findRegistryEntryByCollection = exports.getRealtimeRegistry = exports.updateRealtimeRegistryOptions = exports.registerRealtime = void 0;
4
- var realtimeRegistry = [];
5
- /**
6
- * Register a model for real-time sync. Called automatically by modelRouter
7
- * when the `realtime` option is provided.
8
- */
15
+ var collectionRegistry_1 = require("../collectionRegistry");
16
+ var toRealtimeEntry = function (record) { return ({
17
+ collectionName: record.model.collection.collectionName,
18
+ config: record.options.realtime,
19
+ modelName: record.model.modelName,
20
+ options: record.options,
21
+ 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;
26
+ if (registered) {
27
+ return registered;
28
+ }
29
+ return {
30
+ collection: { collectionName: entry.collectionName },
31
+ modelName: entry.modelName,
32
+ };
33
+ };
9
34
  var registerRealtime = function (entry) {
10
- realtimeRegistry.push(entry);
35
+ (0, collectionRegistry_1.registerCollection)({
36
+ model: realtimeModelForEntry(entry),
37
+ options: __assign(__assign({}, entry.options), { realtime: entry.config }),
38
+ routePath: entry.routePath,
39
+ });
11
40
  };
12
41
  exports.registerRealtime = registerRealtime;
13
- /**
14
- * Replace options on an existing registry entry (e.g. after TerrenoApp injects accessControl).
15
- * Matches by routePath; no-op if the route was never registered.
16
- */
17
42
  var updateRealtimeRegistryOptions = function (routePath, options) {
18
- var existing = realtimeRegistry.find(function (entry) { return entry.routePath === routePath; });
19
- if (!existing) {
20
- return;
21
- }
22
- existing.options = options;
43
+ (0, collectionRegistry_1.replaceCollectionOptions)(routePath, options);
23
44
  };
24
45
  exports.updateRealtimeRegistryOptions = updateRealtimeRegistryOptions;
25
- /**
26
- * Get all registered real-time models.
27
- */
28
- var getRealtimeRegistry = function () { return realtimeRegistry; };
46
+ var getRealtimeRegistry = function () {
47
+ return (0, collectionRegistry_1.listCollections)()
48
+ .filter(function (record) { return record.surfaces.realtime; })
49
+ .map(toRealtimeEntry);
50
+ };
29
51
  exports.getRealtimeRegistry = getRealtimeRegistry;
30
- /**
31
- * Find a registry entry by MongoDB collection name.
32
- */
33
52
  var findRegistryEntryByCollection = function (collectionName) {
34
- return realtimeRegistry.find(function (entry) { return entry.collectionName === collectionName; });
53
+ return (0, exports.getRealtimeRegistry)().find(function (entry) { return entry.collectionName === collectionName; });
35
54
  };
36
55
  exports.findRegistryEntryByCollection = findRegistryEntryByCollection;
37
- /**
38
- * Find a registry entry by route path / collection tag (e.g. "todos").
39
- */
40
56
  var findRegistryEntryByRoutePath = function (collection) {
41
- return realtimeRegistry.find(function (entry) { return entry.routePath === "/".concat(collection) || entry.routePath === collection; });
57
+ return (0, exports.getRealtimeRegistry)().find(function (entry) { return entry.routePath === "/".concat(collection) || entry.routePath === collection; });
42
58
  };
43
59
  exports.findRegistryEntryByRoutePath = findRegistryEntryByRoutePath;
44
- /**
45
- * Clear the registry (for testing).
46
- */
47
60
  var clearRealtimeRegistry = function () {
48
- realtimeRegistry.length = 0;
61
+ (0, collectionRegistry_1.clearCollectionRegistry)();
49
62
  };
50
63
  exports.clearRealtimeRegistry = clearRealtimeRegistry;
@@ -11,9 +11,9 @@ import type { SocketWithDecodedToken } from "./socketUser";
11
11
  * fails, the connection is rejected with the last validator's error.
12
12
  *
13
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.
14
+ * 1. Legacy JWT (when a token secret is configured, always first) — the existing
15
+ * `@thream/socketio-jwt` middleware, wrapped unchanged so accepted payloads, secret
16
+ * handling, and error shapes are byte-for-byte identical to the previous hardcoded setup.
17
17
  * 2. Better Auth session (optional) — enabled via `RealtimeAppOptions.betterAuth`. The
18
18
  * handshake token is validated as a Better Auth session via `auth.api.getSession`
19
19
  * (presented as an `Authorization: Bearer` credential, resolved by Better Auth's
@@ -82,8 +82,8 @@ export declare const createBetterAuthValidator: (options: BetterAuthSocketOption
82
82
  * the first success wins; when all fail the connection is rejected with the last error.
83
83
  */
84
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;
85
+ /** Secret enabling the legacy JWT validator (same handling as before the refactor). */
86
+ tokenSecret?: string;
87
87
  /**
88
88
  * JWT issuer to require (D1 parity with the HTTP path's `jwt.verify(token, secret,
89
89
  * {issuer})`). Omitted means no issuer check, matching pre-D1 behavior. A thunk is
@@ -74,6 +74,7 @@ var __values = (this && this.__values) || function(o) {
74
74
  Object.defineProperty(exports, "__esModule", { value: true });
75
75
  exports.createSocketAuthMiddleware = exports.createBetterAuthValidator = exports.createLegacyJwtValidator = void 0;
76
76
  var socketio_jwt_1 = require("@thream/socketio-jwt");
77
+ var errors_1 = require("../errors");
77
78
  var logger_1 = require("../logger");
78
79
  var plugins_1 = require("../plugins");
79
80
  /**
@@ -211,11 +212,20 @@ exports.createBetterAuthValidator = createBetterAuthValidator;
211
212
  */
212
213
  var createSocketAuthMiddleware = function (_a) {
213
214
  var tokenSecret = _a.tokenSecret, issuer = _a.issuer, betterAuth = _a.betterAuth, _b = _a.extraValidators, extraValidators = _b === void 0 ? [] : _b;
214
- var validators = [(0, exports.createLegacyJwtValidator)(tokenSecret, issuer)];
215
+ var validators = [];
216
+ if (tokenSecret) {
217
+ validators.push((0, exports.createLegacyJwtValidator)(tokenSecret, issuer));
218
+ }
215
219
  if (betterAuth) {
216
220
  validators.push((0, exports.createBetterAuthValidator)(betterAuth));
217
221
  }
218
222
  validators.push.apply(validators, __spreadArray([], __read(extraValidators), false));
223
+ if (validators.length === 0) {
224
+ throw new errors_1.APIError({
225
+ status: 500,
226
+ title: "[realtime] At least one socket authentication validator is required.",
227
+ });
228
+ }
219
229
  return function (socket, next) {
220
230
  void (function () { return __awaiter(void 0, void 0, void 0, function () {
221
231
  var lastError, validators_1, validators_1_1, validator, error_1, e_1_1;
@@ -26,7 +26,11 @@ export interface DecodedRealtimeToken {
26
26
  * configured, or while the handshake load is still in flight.
27
27
  */
28
28
  export interface SocketDataBag {
29
- fullUser?: any;
29
+ /**
30
+ * The consumer's own Mongoose user document, so its app-specific fields are opaque
31
+ * here — read it through {@link getSocketUser} rather than narrowing it inline.
32
+ */
33
+ fullUser?: unknown;
30
34
  /**
31
35
  * The in-flight handshake load of {@link SocketDataBag.fullUser}, published so handlers
32
36
  * that must not authorize against the synthetic token user can await it
@@ -7,6 +7,9 @@ import type { BetterAuthSocketOptions } from "./socketAuth";
7
7
  /**
8
8
  * Configuration for real-time sync on a modelRouter.
9
9
  * Determines which CRUD methods emit WebSocket events and how they are routed.
10
+ *
11
+ * @deprecated Removed in Terreno 58. Use `sync` on modelRouter with `@terreno/syncdb`.
12
+ * `RealtimeApp` remains required for sync sockets.
10
13
  */
11
14
  export interface RealtimeConfig {
12
15
  /** Which CRUD methods should emit real-time sync events */
@@ -24,6 +27,9 @@ export interface RealtimeConfig {
24
27
  }
25
28
  /**
26
29
  * A real-time sync event emitted to clients via WebSocket.
30
+ *
31
+ * @deprecated Removed in Terreno 58 with modelRouter `realtime` and the RTK
32
+ * cache-patching helpers. Syncdb uses `sync:delta` events instead.
27
33
  */
28
34
  export interface RealtimeEvent {
29
35
  /** Mongoose model name (e.g. "Todo") */
@@ -78,7 +84,10 @@ export interface RealtimeAppOptions {
78
84
  adapter?: "redis" | "none";
79
85
  /** Redis URL for the Redis adapter */
80
86
  redisUrl?: string;
81
- /** JWT secret for socket authentication (default: process.env.TOKEN_SECRET) */
87
+ /**
88
+ * JWT secret for socket authentication (default: process.env.TOKEN_SECRET).
89
+ * Optional when `betterAuth` is configured.
90
+ */
82
91
  tokenSecret?: string;
83
92
  /**
84
93
  * JWT issuer required for socket authentication (default: process.env.TOKEN_ISSUER),
@@ -87,9 +96,10 @@ export interface RealtimeAppOptions {
87
96
  */
88
97
  tokenIssuer?: string;
89
98
  /**
90
- * Enables the Better Auth session validator for socket authentication, tried after the
91
- * legacy JWT validator. Pass the instance returned by `createBetterAuth` (and optionally
92
- * the app user model so `decodedToken.id`/`admin` match the REST identity).
99
+ * Enables the Better Auth session validator for socket authentication. It is tried after
100
+ * the legacy JWT validator when a token secret exists, or used alone otherwise. Pass the
101
+ * instance returned by `createBetterAuth` (and optionally the app user model so
102
+ * `decodedToken.id`/`admin` match the REST identity).
93
103
  */
94
104
  betterAuth?: BetterAuthSocketOptions;
95
105
  /**
@@ -0,0 +1,56 @@
1
+ import type { Model } from "mongoose";
2
+ import type { ModelRouterValidationOptions } from "./openApiValidator";
3
+ import type { PopulatePath } from "./populate";
4
+ import type { FieldMask } from "./rbac/types";
5
+ export declare const SYSTEM_FIELD_PATHS: Set<string>;
6
+ export type FieldKind = "string" | "number" | "boolean" | "date" | "dateOnly" | "objectId" | "embedded" | "mixed" | "map";
7
+ export interface FieldDescription {
8
+ kind: FieldKind;
9
+ required: boolean;
10
+ description?: string;
11
+ enum?: string[];
12
+ ref?: string;
13
+ isArray?: boolean;
14
+ item?: FieldDescription;
15
+ fields?: Record<string, FieldDescription>;
16
+ system?: boolean;
17
+ default?: unknown;
18
+ writableOnCreate?: boolean;
19
+ writableOnUpdate?: boolean;
20
+ }
21
+ export interface ModelDescription {
22
+ modelName: string;
23
+ fields: Record<string, FieldDescription>;
24
+ }
25
+ export interface DescribeModelOptions {
26
+ populatePaths?: PopulatePath[];
27
+ extraProperties?: Record<string, FieldDescription>;
28
+ }
29
+ export interface DescribeModelForRouterOptions extends DescribeModelOptions {
30
+ validation?: boolean | ModelRouterValidationOptions;
31
+ excludeFields?: string[];
32
+ fieldView?: FieldMask;
33
+ }
34
+ export declare const nestDottedFieldDescriptions: (fields: Record<string, FieldDescription>) => Record<string, FieldDescription>;
35
+ export declare const describeModel: <T>(model: Model<T>, options?: DescribeModelOptions) => ModelDescription;
36
+ export declare const describeModelForRouter: <T>(model: Model<T>, options?: DescribeModelForRouterOptions) => ModelDescription;
37
+ export declare const fieldDescriptionToOpenApiProperty: (field: FieldDescription) => Record<string, unknown>;
38
+ export declare const modelDescriptionToOpenApiSpec: (description: ModelDescription) => {
39
+ properties: Record<string, unknown>;
40
+ required: string[];
41
+ };
42
+ export declare const fieldDescriptionToAdminMeta: (field: FieldDescription) => {
43
+ default?: unknown;
44
+ description?: string;
45
+ enum?: string[];
46
+ itemEnum?: string[];
47
+ itemRef?: string;
48
+ itemType?: string;
49
+ items?: Record<string, ReturnType<typeof fieldDescriptionToAdminMeta>>;
50
+ ref?: string;
51
+ required: boolean;
52
+ searchable?: boolean;
53
+ type: string;
54
+ };
55
+ export declare const modelDescriptionToAdminFields: (description: ModelDescription) => Record<string, ReturnType<typeof fieldDescriptionToAdminMeta>>;
56
+ export declare const fieldDescriptionToZodType: (field: FieldDescription, z: typeof import("zod").z) => import("zod").ZodType;