@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
package/dist/populate.js CHANGED
@@ -54,6 +54,7 @@ exports.unpopulate = exports.getOpenApiSpecForModel = exports.fixMixedFields = v
54
54
  var isArray_1 = __importDefault(require("lodash/isArray"));
55
55
  var mongoose_to_swagger_1 = __importDefault(require("mongoose-to-swagger"));
56
56
  var errors_1 = require("./errors");
57
+ var schemaMetadata_1 = require("./schemaMetadata");
57
58
  var m2sOptions = {
58
59
  props: ["readOnly", "required", "enum", "default"],
59
60
  };
@@ -157,17 +158,18 @@ var fixMixedFields = function (schema, properties) {
157
158
  }
158
159
  };
159
160
  exports.fixMixedFields = fixMixedFields;
160
- var getOpenApiSpecForModel = function (
161
- // noExplicitAny: Mongoose Model param uses deep internal APIs (schema.path().options.ref, schema.virtuals, schema.childSchemas, db.model) that are not exposed in public type definitions
162
- // biome-ignore lint/suspicious/noExplicitAny: Mongoose Model param uses deep internal APIs (schema.path().options.ref, schema.virtuals, schema.childSchemas, db.model) that are not exposed in public type definitions
163
- model, _a) {
161
+ var getOpenApiSpecForModel = function (model, _a) {
164
162
  var e_2, _b, _c, e_3, _d, e_4, _e, e_5, _f;
165
- var _g, _h, _j, _k;
166
- var _l = _a === void 0 ? {} : _a, populatePaths = _l.populatePaths, extraModelProperties = _l.extraModelProperties;
167
- var modelSwagger = (0, mongoose_to_swagger_1.default)(model, {
168
- props: ["required", "enum"],
169
- });
170
- (0, exports.fixMixedFields)(model.schema, modelSwagger.properties);
163
+ var _g, _h, _j, _k, _l, _m;
164
+ var _o = _a === void 0 ? {} : _a, populatePaths = _o.populatePaths, extraModelProperties = _o.extraModelProperties;
165
+ var description = (0, schemaMetadata_1.describeModel)(model);
166
+ var _p = (0, schemaMetadata_1.modelDescriptionToOpenApiSpec)(description), properties = _p.properties, required = _p.required;
167
+ var modelProperties = properties;
168
+ var modelSwagger = {
169
+ properties: modelProperties,
170
+ required: required,
171
+ };
172
+ (0, exports.fixMixedFields)(model.schema, modelProperties);
171
173
  if (populatePaths && (0, isArray_1.default)(populatePaths)) {
172
174
  try {
173
175
  for (var populatePaths_1 = __values(populatePaths), populatePaths_1_1 = populatePaths_1.next(); !populatePaths_1_1.done; populatePaths_1_1 = populatePaths_1.next()) {
@@ -182,7 +184,7 @@ model, _a) {
182
184
  continue;
183
185
  }
184
186
  // Get the properties of the referenced model
185
- var properties = filterKeys((0, mongoose_to_swagger_1.default)(model.db.model(populateModel), m2sOptions).properties, populatePath.fields);
187
+ var properties_1 = filterKeys((0, mongoose_to_swagger_1.default)(model.db.model(populateModel), m2sOptions).properties, populatePath.fields);
186
188
  // Get the OpenAPI path for the current populate path
187
189
  var openApiPath = getPathInSchema(modelSwagger, populatePath.path);
188
190
  // Determine the schema to set
@@ -194,7 +196,7 @@ model, _a) {
194
196
  }
195
197
  else {
196
198
  schemaToSet = {
197
- properties: properties,
199
+ properties: properties_1,
198
200
  type: "object",
199
201
  };
200
202
  }
@@ -223,7 +225,8 @@ model, _a) {
223
225
  currentSchema[part] = { properties: {}, type: "object" };
224
226
  }
225
227
  }
226
- currentSchema = currentSchema[part].properties || currentSchema[part];
228
+ var nextSchema = (_k = currentSchema[part].properties) !== null && _k !== void 0 ? _k : currentSchema[part];
229
+ currentSchema = nextSchema;
227
230
  }
228
231
  }
229
232
  }
@@ -238,8 +241,8 @@ model, _a) {
238
241
  }
239
242
  try {
240
243
  // Add virtuals to the modelSwagger property
241
- for (var _m = __values(Object.keys(model.schema.virtuals)), _o = _m.next(); !_o.done; _o = _m.next()) {
242
- var virtual = _o.value;
244
+ for (var _q = __values(Object.keys(model.schema.virtuals)), _r = _q.next(); !_r.done; _r = _q.next()) {
245
+ var virtual = _r.value;
243
246
  // Skip Mongoose internals
244
247
  if (virtual === "id" || virtual === "__v") {
245
248
  continue;
@@ -252,22 +255,26 @@ model, _a) {
252
255
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
253
256
  finally {
254
257
  try {
255
- if (_o && !_o.done && (_d = _m.return)) _d.call(_m);
258
+ if (_r && !_r.done && (_d = _q.return)) _d.call(_q);
256
259
  }
257
260
  finally { if (e_3) throw e_3.error; }
258
261
  }
259
262
  // Check subschemas for virtuals (one level deep)
260
263
  if (model.schema.childSchemas.length > 0) {
261
264
  try {
262
- for (var _p = __values(model.schema.childSchemas), _q = _p.next(); !_q.done; _q = _p.next()) {
263
- var childSchema = _q.value;
265
+ for (var _s = __values(model.schema.childSchemas), _t = _s.next(); !_t.done; _t = _s.next()) {
266
+ var childSchema = _t.value;
264
267
  try {
265
- for (var _r = (e_5 = void 0, __values(Object.keys(childSchema.schema.virtuals))), _s = _r.next(); !_s.done; _s = _r.next()) {
266
- var virtual = _s.value;
268
+ for (var _u = (e_5 = void 0, __values(Object.keys(childSchema.schema.virtuals))), _v = _u.next(); !_v.done; _v = _u.next()) {
269
+ var virtual = _v.value;
267
270
  if (virtual === "id" || virtual === "__v") {
268
271
  continue;
269
272
  }
270
- modelSwagger.properties[childSchema.model.path].properties[virtual] = {
273
+ var childPath = childSchema.model.path;
274
+ if (!childPath || !((_l = modelSwagger.properties[childPath]) === null || _l === void 0 ? void 0 : _l.properties)) {
275
+ continue;
276
+ }
277
+ modelSwagger.properties[childPath].properties[virtual] = {
271
278
  type: "any",
272
279
  };
273
280
  }
@@ -275,7 +282,7 @@ model, _a) {
275
282
  catch (e_5_1) { e_5 = { error: e_5_1 }; }
276
283
  finally {
277
284
  try {
278
- if (_s && !_s.done && (_f = _r.return)) _f.call(_r);
285
+ if (_v && !_v.done && (_f = _u.return)) _f.call(_u);
279
286
  }
280
287
  finally { if (e_5) throw e_5.error; }
281
288
  }
@@ -284,14 +291,14 @@ model, _a) {
284
291
  catch (e_4_1) { e_4 = { error: e_4_1 }; }
285
292
  finally {
286
293
  try {
287
- if (_q && !_q.done && (_e = _p.return)) _e.call(_p);
294
+ if (_t && !_t.done && (_e = _s.return)) _e.call(_s);
288
295
  }
289
296
  finally { if (e_4) throw e_4.error; }
290
297
  }
291
298
  }
292
299
  return {
293
300
  properties: __assign(__assign({}, modelSwagger.properties), extraModelProperties),
294
- required: (_k = modelSwagger.required) !== null && _k !== void 0 ? _k : [],
301
+ required: (_m = modelSwagger.required) !== null && _m !== void 0 ? _m : [],
295
302
  };
296
303
  };
297
304
  exports.getOpenApiSpecForModel = getOpenApiSpecForModel;
@@ -304,53 +311,51 @@ var unpopulate = function (doc, path) {
304
311
  throw new errors_1.APIError({ status: 500, title: "path is required for unpopulate" });
305
312
  }
306
313
  var pathParts = path.split(".");
314
+ var asRecord = function (value) { return value; };
315
+ var idOf = function (value) { return value === null || value === void 0 ? void 0 : value._id; };
307
316
  // Recursive because we need to support nested paths.
308
- // noExplicitAny: recursive document traversal uses bracket-notation indexing on arbitrary nested document shapes that Mongoose Document types do not expose
309
- // biome-ignore lint/suspicious/noExplicitAny: recursive document traversal uses bracket-notation indexing on arbitrary nested document shapes that Mongoose Document types do not expose
310
317
  var recursiveUnpopulate = function (current, parts) {
311
318
  var e_6, _a;
312
- var _b;
313
319
  var part = parts[0];
320
+ var value = current[part];
314
321
  // If the path doesn't exist, return the original doc
315
- if (!current[part]) {
316
- return doc;
322
+ if (!value) {
323
+ return asRecord(doc);
317
324
  }
318
325
  if (parts.length === 1) {
319
326
  // Base case: we've reached the last part of the path
320
- if (Array.isArray(current[part])) {
327
+ if (Array.isArray(value)) {
321
328
  // If the field is an array, recursively unpopulate each element
322
- current[part] = current[part].map(function (item) {
323
- return (item === null || item === void 0 ? void 0 : item._id) ? item._id : item;
324
- });
329
+ current[part] = value.map(function (item) { var _a; return (_a = idOf(item)) !== null && _a !== void 0 ? _a : item; });
325
330
  }
326
- else if ((_b = current[part]) === null || _b === void 0 ? void 0 : _b._id) {
331
+ else if (idOf(value)) {
327
332
  // If the field is a populated document, revert to _id
328
- current[part] = current[part]._id;
333
+ current[part] = idOf(value);
329
334
  }
330
335
  }
331
336
  else {
332
337
  // Recursive case: continue down the path
333
- if (Array.isArray(current[part])) {
338
+ if (Array.isArray(value)) {
334
339
  try {
335
- for (var _c = __values(current[part]), _d = _c.next(); !_d.done; _d = _c.next()) {
336
- var item = _d.value;
337
- recursiveUnpopulate(item, parts.slice(1)); // Recursively handle each item in the array
340
+ for (var value_1 = __values(value), value_1_1 = value_1.next(); !value_1_1.done; value_1_1 = value_1.next()) {
341
+ var item = value_1_1.value;
342
+ recursiveUnpopulate(asRecord(item), parts.slice(1)); // Recursively handle each item in the array
338
343
  }
339
344
  }
340
345
  catch (e_6_1) { e_6 = { error: e_6_1 }; }
341
346
  finally {
342
347
  try {
343
- if (_d && !_d.done && (_a = _c.return)) _a.call(_c);
348
+ if (value_1_1 && !value_1_1.done && (_a = value_1.return)) _a.call(value_1);
344
349
  }
345
350
  finally { if (e_6) throw e_6.error; }
346
351
  }
347
352
  }
348
353
  else {
349
- recursiveUnpopulate(current[part], parts.slice(1)); // Recursively handle the next part
354
+ recursiveUnpopulate(asRecord(value), parts.slice(1)); // Recursively handle the next part
350
355
  }
351
356
  }
352
357
  return current;
353
358
  };
354
- return recursiveUnpopulate(doc, pathParts);
359
+ return recursiveUnpopulate(asRecord(doc), pathParts);
355
360
  };
356
361
  exports.unpopulate = unpopulate;
@@ -0,0 +1,3 @@
1
+ import type { Application } from "express";
2
+ import type { RateLimitOptions } from "./types";
3
+ export declare const applyRateLimitTrustProxy: (app: Application, options: RateLimitOptions) => void;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.applyRateLimitTrustProxy = void 0;
4
+ var applyRateLimitTrustProxy = function (app, options) {
5
+ if (options.trustProxy === false) {
6
+ app.set("trust proxy", false);
7
+ return;
8
+ }
9
+ if (options.trustProxy !== undefined) {
10
+ app.set("trust proxy", options.trustProxy);
11
+ return;
12
+ }
13
+ // Default off so client X-Forwarded-For cannot rotate unauthenticated buckets.
14
+ // Cloud Run / GFE: pass trustProxy: 1.
15
+ app.set("trust proxy", false);
16
+ };
17
+ exports.applyRateLimitTrustProxy = applyRateLimitTrustProxy;
@@ -0,0 +1,2 @@
1
+ import type { RateLimitOptions, RateLimitStore } from "./types";
2
+ export declare const createRateLimitStore: (options: RateLimitOptions) => RateLimitStore;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRateLimitStore = void 0;
4
+ var errors_1 = require("../errors");
5
+ var memoryStore_1 = require("./memoryStore");
6
+ var mongoStore_1 = require("./mongoStore");
7
+ var redisStore_1 = require("./redisStore");
8
+ var createRateLimitStore = function (options) {
9
+ var _a;
10
+ if (options.storeImpl) {
11
+ return options.storeImpl;
12
+ }
13
+ var kind = (_a = options.store) !== null && _a !== void 0 ? _a : "memory";
14
+ if (kind === "memory") {
15
+ return (0, memoryStore_1.createMemoryRateLimitStore)();
16
+ }
17
+ if (kind === "redis") {
18
+ return (0, redisStore_1.createRedisRateLimitStore)(options);
19
+ }
20
+ if (kind === "mongo") {
21
+ return (0, mongoStore_1.createMongoRateLimitStore)();
22
+ }
23
+ throw new errors_1.APIError({
24
+ status: 500,
25
+ title: "Unknown rate limit store: ".concat(String(kind)),
26
+ });
27
+ };
28
+ exports.createRateLimitStore = createRateLimitStore;
@@ -0,0 +1,2 @@
1
+ import type { RateLimitStore } from "./types";
2
+ export declare const createMemoryRateLimitStore: () => RateLimitStore;
@@ -0,0 +1,108 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
66
+ exports.createMemoryRateLimitStore = void 0;
67
+ var createMemoryRateLimitStore = function () {
68
+ var windows = new Map();
69
+ var consume = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
70
+ var existing, windows_1, windows_1_1, _c, windowKey, window_1, resetAt, allowed;
71
+ var e_1, _d;
72
+ var key = _b.key, max = _b.max, windowMs = _b.windowMs, now = _b.now;
73
+ return __generator(this, function (_e) {
74
+ existing = windows.get(key);
75
+ if (!existing || existing.resetAt <= now) {
76
+ if (windows.size > 10000) {
77
+ try {
78
+ for (windows_1 = __values(windows), windows_1_1 = windows_1.next(); !windows_1_1.done; windows_1_1 = windows_1.next()) {
79
+ _c = __read(windows_1_1.value, 2), windowKey = _c[0], window_1 = _c[1];
80
+ if (window_1.resetAt <= now) {
81
+ windows.delete(windowKey);
82
+ }
83
+ }
84
+ }
85
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
86
+ finally {
87
+ try {
88
+ if (windows_1_1 && !windows_1_1.done && (_d = windows_1.return)) _d.call(windows_1);
89
+ }
90
+ finally { if (e_1) throw e_1.error; }
91
+ }
92
+ }
93
+ resetAt = now + windowMs;
94
+ windows.set(key, { count: 1, resetAt: resetAt });
95
+ return [2 /*return*/, { allowed: true, remaining: Math.max(0, max - 1), resetAt: resetAt }];
96
+ }
97
+ existing.count += 1;
98
+ allowed = existing.count <= max;
99
+ return [2 /*return*/, {
100
+ allowed: allowed,
101
+ remaining: Math.max(0, max - existing.count),
102
+ resetAt: existing.resetAt,
103
+ }];
104
+ });
105
+ }); };
106
+ return { consume: consume };
107
+ };
108
+ exports.createMemoryRateLimitStore = createMemoryRateLimitStore;
@@ -0,0 +1,11 @@
1
+ import type { NextFunction, Request, Response } from "express";
2
+ import type { RateLimitOptions, RateLimitStore } from "./types";
3
+ export declare const setRateLimitExceededHeaders: ({ max, remaining, resetAt, now, windowMs, res, }: {
4
+ max: number;
5
+ remaining: number;
6
+ resetAt: number;
7
+ now: number;
8
+ windowMs: number;
9
+ res: Response;
10
+ }) => void;
11
+ export declare const createRateLimitMiddleware: (store: RateLimitStore, options?: RateLimitOptions) => ((req: Request, res: Response, next: NextFunction) => Promise<void>);
@@ -0,0 +1,110 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.createRateLimitMiddleware = exports.setRateLimitExceededHeaders = void 0;
40
+ var luxon_1 = require("luxon");
41
+ var errors_1 = require("../errors");
42
+ var policies_1 = require("./policies");
43
+ var types_1 = require("./types");
44
+ var secondsUntil = function (resetAt, now) {
45
+ return Math.max(1, Math.ceil((resetAt - now) / 1000));
46
+ };
47
+ var setRateLimitExceededHeaders = function (_a) {
48
+ var max = _a.max, remaining = _a.remaining, resetAt = _a.resetAt, now = _a.now, windowMs = _a.windowMs, res = _a.res;
49
+ var retryAfter = secondsUntil(resetAt, now);
50
+ var windowSec = Math.max(1, Math.ceil(windowMs / 1000));
51
+ res.setHeader("Retry-After", String(retryAfter));
52
+ res.setHeader("RateLimit", "limit=".concat(max, ", remaining=").concat(remaining, ", reset=").concat(retryAfter));
53
+ res.setHeader("RateLimit-Policy", "".concat(max, ";w=").concat(windowSec));
54
+ };
55
+ exports.setRateLimitExceededHeaders = setRateLimitExceededHeaders;
56
+ var createRateLimitMiddleware = function (store, options) {
57
+ var _a, _b, _c, _d, _e, _f, _g;
58
+ if (options === void 0) { options = {}; }
59
+ var windowMs = (_b = (_a = options.limits) === null || _a === void 0 ? void 0 : _a.windowMs) !== null && _b !== void 0 ? _b : types_1.DEFAULT_WINDOW_MS;
60
+ var authMax = (_d = (_c = options.limits) === null || _c === void 0 ? void 0 : _c.authMax) !== null && _d !== void 0 ? _d : types_1.DEFAULT_AUTH_MAX;
61
+ var apiMax = (_f = (_e = options.limits) === null || _e === void 0 ? void 0 : _e.apiMax) !== null && _f !== void 0 ? _f : types_1.DEFAULT_API_MAX;
62
+ var betterAuthBasePath = options.betterAuthBasePath;
63
+ var nowFn = (_g = options.now) !== null && _g !== void 0 ? _g : (function () { return luxon_1.DateTime.now().toMillis(); });
64
+ return function (req, res, next) { return __awaiter(void 0, void 0, void 0, function () {
65
+ var policy, max, key, now, result, error_1;
66
+ return __generator(this, function (_a) {
67
+ switch (_a.label) {
68
+ case 0:
69
+ if ((0, policies_1.shouldSkipRateLimit)(req, options.skip)) {
70
+ next();
71
+ return [2 /*return*/];
72
+ }
73
+ policy = (0, policies_1.classifyRateLimitPolicy)(req, betterAuthBasePath);
74
+ max = policy === "auth" ? authMax : apiMax;
75
+ key = "".concat(policy, ":").concat((0, policies_1.rateLimitKey)(req, policy));
76
+ now = nowFn();
77
+ _a.label = 1;
78
+ case 1:
79
+ _a.trys.push([1, 3, , 4]);
80
+ return [4 /*yield*/, store.consume({ key: key, max: max, now: now, windowMs: windowMs })];
81
+ case 2:
82
+ result = _a.sent();
83
+ if (result.allowed) {
84
+ next();
85
+ return [2 /*return*/];
86
+ }
87
+ (0, exports.setRateLimitExceededHeaders)({
88
+ max: max,
89
+ now: now,
90
+ remaining: result.remaining,
91
+ res: res,
92
+ resetAt: result.resetAt,
93
+ windowMs: windowMs,
94
+ });
95
+ next(new errors_1.APIError({
96
+ code: "rate-limit-exceeded",
97
+ status: 429,
98
+ title: "Too many requests",
99
+ }));
100
+ return [3 /*break*/, 4];
101
+ case 3:
102
+ error_1 = _a.sent();
103
+ next(error_1);
104
+ return [3 /*break*/, 4];
105
+ case 4: return [2 /*return*/];
106
+ }
107
+ });
108
+ }); };
109
+ };
110
+ exports.createRateLimitMiddleware = createRateLimitMiddleware;
@@ -0,0 +1,3 @@
1
+ import type { RateLimitStore } from "./types";
2
+ export declare const RATE_LIMIT_HITS_COLLECTION = "rateLimitHits";
3
+ export declare const createMongoRateLimitStore: () => RateLimitStore;
@@ -0,0 +1,122 @@
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 __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ exports.createMongoRateLimitStore = exports.RATE_LIMIT_HITS_COLLECTION = void 0;
43
+ var luxon_1 = require("luxon");
44
+ var mongoose_1 = __importDefault(require("mongoose"));
45
+ var errors_1 = require("../errors");
46
+ exports.RATE_LIMIT_HITS_COLLECTION = "rateLimitHits";
47
+ var ensureIndexes = function (collection) { return __awaiter(void 0, void 0, void 0, function () {
48
+ return __generator(this, function (_a) {
49
+ switch (_a.label) {
50
+ case 0: return [4 /*yield*/, collection.createIndex({ key: 1 }, { unique: true })];
51
+ case 1:
52
+ _a.sent();
53
+ return [4 /*yield*/, collection.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })];
54
+ case 2:
55
+ _a.sent();
56
+ return [2 /*return*/];
57
+ }
58
+ });
59
+ }); };
60
+ var createMongoRateLimitStore = function () {
61
+ var indexed = false;
62
+ var consume = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
63
+ var db, collection, nowDate, resetAtDate, updated, hits, expiresAt, resetAt;
64
+ var _c;
65
+ var key = _b.key, max = _b.max, windowMs = _b.windowMs, now = _b.now;
66
+ return __generator(this, function (_d) {
67
+ switch (_d.label) {
68
+ case 0:
69
+ db = mongoose_1.default.connection.db;
70
+ if (!db) {
71
+ throw new errors_1.APIError({
72
+ status: 500,
73
+ title: "Mongo rate limit store requires an open mongoose connection",
74
+ });
75
+ }
76
+ collection = db.collection(exports.RATE_LIMIT_HITS_COLLECTION);
77
+ if (!!indexed) return [3 /*break*/, 2];
78
+ return [4 /*yield*/, ensureIndexes(collection)];
79
+ case 1:
80
+ _d.sent();
81
+ indexed = true;
82
+ _d.label = 2;
83
+ case 2:
84
+ nowDate = luxon_1.DateTime.fromMillis(now).toJSDate();
85
+ resetAtDate = luxon_1.DateTime.fromMillis(now + windowMs).toJSDate();
86
+ return [4 /*yield*/, collection.findOneAndUpdate({ key: key }, [
87
+ {
88
+ $set: {
89
+ expiresAt: {
90
+ $cond: [
91
+ { $and: [{ $ne: ["$expiresAt", null] }, { $gt: ["$expiresAt", nowDate] }] },
92
+ "$expiresAt",
93
+ resetAtDate,
94
+ ],
95
+ },
96
+ hits: {
97
+ $cond: [
98
+ { $and: [{ $ne: ["$expiresAt", null] }, { $gt: ["$expiresAt", nowDate] }] },
99
+ { $add: [{ $ifNull: ["$hits", 0] }, 1] },
100
+ 1,
101
+ ],
102
+ },
103
+ key: key,
104
+ },
105
+ },
106
+ ], { returnDocument: "after", upsert: true })];
107
+ case 3:
108
+ updated = _d.sent();
109
+ hits = Number((_c = updated === null || updated === void 0 ? void 0 : updated.hits) !== null && _c !== void 0 ? _c : 1);
110
+ expiresAt = updated === null || updated === void 0 ? void 0 : updated.expiresAt;
111
+ resetAt = expiresAt != null ? luxon_1.DateTime.fromJSDate(expiresAt).toMillis() : now + windowMs;
112
+ return [2 /*return*/, {
113
+ allowed: hits <= max,
114
+ remaining: Math.max(0, max - hits),
115
+ resetAt: resetAt,
116
+ }];
117
+ }
118
+ });
119
+ }); };
120
+ return { consume: consume };
121
+ };
122
+ exports.createMongoRateLimitStore = createMongoRateLimitStore;
@@ -0,0 +1,14 @@
1
+ import type { Request } from "express";
2
+ import type { RateLimitPolicyName } from "./types";
3
+ /** Strip query, fragment, and a trailing slash so `/auth/login/` matches `/auth/login`. */
4
+ export declare const normalizeRequestPath: (url: string) => string;
5
+ /** Prefer Express `req.path` (routing) over the raw request-target. */
6
+ export declare const requestPath: (req: Request) => string;
7
+ /**
8
+ * JWT login, signup, and refresh must not 401 on a stale access token.
9
+ * `setupAuth` runs before those routes so the client can still exchange credentials.
10
+ */
11
+ export declare const isJwtCredentialExchangePath: (req: Request) => boolean;
12
+ export declare const shouldSkipRateLimit: (req: Request, extraSkip?: (req: Request) => boolean) => boolean;
13
+ export declare const classifyRateLimitPolicy: (req: Request, betterAuthBasePath?: string) => RateLimitPolicyName;
14
+ export declare const rateLimitKey: (req: Request, policy: RateLimitPolicyName) => string;