@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/src/terrenoApp.ts CHANGED
@@ -7,8 +7,16 @@ import qs from "qs";
7
7
  import type {AdminChangeEvent, TerrenoAppAdminEvent} from "./adminTypes";
8
8
  import type {ModelRouterRegistration} from "./api";
9
9
  import {addAuthRoutes, addMeRoutes, setupAuth, type UserModel as UserMongooseModel} from "./auth";
10
- import type {BetterAuthInstance} from "./betterAuthSetup";
11
- import {ConfigurationApp, type ConfigurationAppOptions} from "./configurationApp";
10
+ import {
11
+ applyJwtPasswordResetToBetterAuth,
12
+ type BetterAuthInstance,
13
+ createBetterAuthSessionMiddleware,
14
+ } from "./betterAuthSetup";
15
+ import {
16
+ ConfigurationApp,
17
+ type ConfigurationAppOptions,
18
+ type ConfigurationModelLike,
19
+ } from "./configurationApp";
12
20
  import {
13
21
  apiErrorMiddleware,
14
22
  apiFallthroughErrorMiddleware,
@@ -18,9 +26,18 @@ import {type AddRoutes, type AuthOptions, logRequests} from "./expressServer";
18
26
  import {addGitHubAuthRoutes, type GitHubAuthOptions, setupGitHubAuth} from "./githubAuth";
19
27
  import {type LoggingOptions, logger, setupLogging} from "./logger";
20
28
  import {mountMCPServer} from "./mcp/server";
29
+ import {
30
+ addMcpServiceTokenRoutes,
31
+ type McpServiceTokensAppOption,
32
+ resolveMcpServiceTokensOption,
33
+ } from "./mcp/serviceTokens";
21
34
  import {jsonResponseRequestIdMiddleware} from "./middleware";
22
35
  import {openApiCompatMiddleware, patchAppUse} from "./openApiCompat";
23
36
  import {openApiEtagMiddleware} from "./openApiEtag";
37
+ import {applyRateLimitTrustProxy} from "./rateLimit/applyTrustProxy";
38
+ import {createRateLimitStore} from "./rateLimit/createStore";
39
+ import {createRateLimitMiddleware} from "./rateLimit/middleware";
40
+ import type {RateLimitOptions} from "./rateLimit/types";
24
41
  import {RealtimeApp} from "./realtime/realtimeApp";
25
42
  import type {RealtimeAppOptions} from "./realtime/types";
26
43
  import {
@@ -31,10 +48,14 @@ import {
31
48
  import {ensureSyncIndexes} from "./sync/registry";
32
49
  import type {TerrenoPlugin} from "./terrenoPlugin";
33
50
  import openapi from "./vendor/wesleytodd-openapi/index";
51
+ import {jsonBodyParserOptions, urlencodedBodyParserOptions} from "./webhooks/rawBody";
34
52
 
35
53
  /** A registered plugin that exposes a Better Auth instance, e.g. BetterAuthApp. */
36
54
  interface BetterAuthProvider {
37
55
  getAuth: () => BetterAuthInstance | undefined;
56
+ ensureAuth?: () => BetterAuthInstance;
57
+ markSessionMiddlewareMounted?: () => void;
58
+ getBetterAuthBasePath?: () => string;
38
59
  }
39
60
 
40
61
  type CorsOrigin =
@@ -93,6 +114,17 @@ export interface TerrenoAppOptions {
93
114
  * Receives the Express app and OpenAPI bundle for `modelRouter` / `createOpenApiBuilder` wiring.
94
115
  */
95
116
  configureApp?: AddRoutes;
117
+ /**
118
+ * Optional HTTP rate limiting. Omitted or `undefined` leaves the limiter off
119
+ * (Terreno 58 will default it on). Pass `{}` or `{store, limits, trustProxy}`
120
+ * to enable. See [Rate limiting](../how-to/rate-limiting.md).
121
+ */
122
+ rateLimit?: RateLimitOptions;
123
+ /**
124
+ * Opt-in personal MCP service tokens. `true` is `{enabled: true}`. When enabled,
125
+ * mounts `/mcp/service-tokens` and accepts `Authorization: Bearer mcp_…` on `/mcp`.
126
+ */
127
+ mcpServiceTokens?: McpServiceTokensAppOption;
96
128
  }
97
129
 
98
130
  /**
@@ -106,7 +138,7 @@ export interface TerrenoAppOptions {
106
138
  * 1. CORS
107
139
  * 2. Optional `beforeJsonSetup` (configure the app before JSON parsing)
108
140
  * 3. Custom middleware (via addMiddleware)
109
- * 4. JSON body parser
141
+ * 4. JSON and urlencoded body parsers (stash `req.rawBody`)
110
142
  * 5. Auth routes (/auth/login, /auth/signup, etc.)
111
143
  * 6. JWT authentication setup
112
144
  * 7. Request logging
@@ -274,12 +306,7 @@ export class TerrenoApp {
274
306
  * .start();
275
307
  * ```
276
308
  */
277
- configure(
278
- // noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
279
- // biome-ignore lint/suspicious/noExplicitAny: Model<any> required for invariance — consumers pass arbitrary configuration models
280
- model: import("mongoose").Model<any>,
281
- options?: Omit<ConfigurationAppOptions, "model">
282
- ): this {
309
+ configure(model: ConfigurationModelLike, options?: Omit<ConfigurationAppOptions, "model">): this {
283
310
  this.configurationApp = new ConfigurationApp({model, ...options});
284
311
  return this;
285
312
  }
@@ -288,8 +315,9 @@ export class TerrenoApp {
288
315
  * Build the Express application without starting the server.
289
316
  *
290
317
  * Configures the complete middleware stack including:
291
- * - CORS, JSON parsing, authentication, logging, Sentry, OpenAPI
292
- * - All registered model routers and plugins
318
+ * - CORS, JSON parsing, JWT decode, optional HTTP rate limiting, auth routes
319
+ * - Better Auth session (when BetterAuthApp is registered) before the limiter
320
+ * - Logging, Sentry, OpenAPI, model routers and plugins
293
321
  * - Error handling middleware
294
322
  *
295
323
  * Use this method when you need the Express app instance for testing
@@ -339,16 +367,46 @@ export class TerrenoApp {
339
367
  }
340
368
  }
341
369
 
342
- app.use(express.json({limit: "50mb"}));
370
+ app.use(express.json(jsonBodyParserOptions));
371
+ app.use(express.urlencoded(urlencodedBodyParserOptions) as unknown as express.RequestHandler);
343
372
 
344
- // Auth routes (login/signup/refresh_token) before JWT middleware
345
- addAuthRoutes(app, options.userModel, options.authOptions);
373
+ // JWT decode before rate limiting so authenticated keys use userId.
374
+ // Auth routes mount after the limiter so login is in the auth bucket.
346
375
  setupAuth(app, options.userModel);
347
376
  app.use((req, res, next) => {
348
377
  updateRequestContextFromRequest(req, res);
349
378
  next();
350
379
  });
351
380
 
381
+ const betterAuthForLimiter = this.registrations.find(
382
+ (registration) =>
383
+ "getAuth" in registration &&
384
+ typeof (registration as Partial<BetterAuthProvider>).getAuth === "function"
385
+ ) as BetterAuthProvider | undefined;
386
+ if (betterAuthForLimiter?.ensureAuth) {
387
+ const auth = betterAuthForLimiter.ensureAuth();
388
+ app.use(createBetterAuthSessionMiddleware(auth, options.userModel));
389
+ betterAuthForLimiter.markSessionMiddlewareMounted?.();
390
+ }
391
+
392
+ if (options.rateLimit) {
393
+ const betterAuthBasePath =
394
+ options.rateLimit.betterAuthBasePath ?? betterAuthForLimiter?.getBetterAuthBasePath?.();
395
+ const rateLimit = {
396
+ ...options.rateLimit,
397
+ ...(betterAuthBasePath ? {betterAuthBasePath} : {}),
398
+ };
399
+ applyRateLimitTrustProxy(app, rateLimit);
400
+ const store = createRateLimitStore(rateLimit);
401
+ app.use(createRateLimitMiddleware(store, rateLimit));
402
+ }
403
+
404
+ if (!options.authOptions) {
405
+ options.authOptions = {};
406
+ }
407
+ const authOptions = options.authOptions;
408
+ addAuthRoutes(app, options.userModel, authOptions);
409
+
352
410
  if (options.logRequests !== false) {
353
411
  app.use(logRequests);
354
412
  }
@@ -429,8 +487,22 @@ export class TerrenoApp {
429
487
  "getAuth" in registration &&
430
488
  typeof (registration as Partial<BetterAuthProvider>).getAuth === "function"
431
489
  ) as BetterAuthProvider | undefined;
490
+ const betterAuth = betterAuthPlugin?.ensureAuth?.() ?? betterAuthPlugin?.getAuth();
491
+ if (betterAuth) {
492
+ authOptions.syncPasswordResetToBetterAuth = async (user, password): Promise<void> => {
493
+ await applyJwtPasswordResetToBetterAuth(betterAuth, user, password);
494
+ };
495
+ }
496
+ const mcpServiceTokens = resolveMcpServiceTokensOption(options.mcpServiceTokens);
497
+ if (mcpServiceTokens.enabled) {
498
+ addMcpServiceTokenRoutes(app, {
499
+ openApi: oapi,
500
+ publicMcpUrl: mcpServiceTokens.publicMcpUrl,
501
+ });
502
+ }
432
503
  mountMCPServer(app, {
433
- betterAuth: betterAuthPlugin?.getAuth(),
504
+ betterAuth,
505
+ mcpServiceTokens: mcpServiceTokens.enabled,
434
506
  userModel: options.userModel,
435
507
  });
436
508
 
@@ -1,7 +1,12 @@
1
1
  import mongoose, {type Model, model, Schema, type StringSchemaDefinition} from "mongoose";
2
2
  import passportLocalMongoose from "passport-local-mongoose";
3
3
 
4
- import {createdUpdatedPlugin, DateOnly, isDisabledPlugin} from "../plugins";
4
+ import {
5
+ createdUpdatedPlugin,
6
+ DateOnly,
7
+ emailVerificationPlugin,
8
+ isDisabledPlugin,
9
+ } from "../plugins";
5
10
 
6
11
  export interface User {
7
12
  admin: boolean;
@@ -11,6 +16,8 @@ export interface User {
11
16
  age?: number;
12
17
  disabled?: boolean;
13
18
  organizationIds?: string[];
19
+ tokenEpoch?: number;
20
+ emailVerified?: boolean;
14
21
  }
15
22
 
16
23
  export interface SuperUser extends User {
@@ -63,6 +70,11 @@ const userSchema = new Schema<User>({
63
70
  description: "Organization memberships",
64
71
  type: [String],
65
72
  },
73
+ tokenEpoch: {
74
+ default: 0,
75
+ description: "Incremented on password reset to invalidate outstanding refresh tokens",
76
+ type: Number,
77
+ },
66
78
  username: {description: "The user's username", type: String},
67
79
  });
68
80
 
@@ -80,6 +92,7 @@ userSchema.plugin(
80
92
  );
81
93
  userSchema.plugin(createdUpdatedPlugin);
82
94
  userSchema.plugin(isDisabledPlugin);
95
+ userSchema.plugin(emailVerificationPlugin);
83
96
  userSchema.methods.postCreate = async function (body: {age?: number}) {
84
97
  this.age = body.age;
85
98
  return this.save();
@@ -0,0 +1,43 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+
4
+ export type AuthTokenType = "passwordReset" | "emailVerification";
5
+
6
+ export type AuthTokenMethods = Record<string, never>;
7
+
8
+ export interface AuthTokenStatics
9
+ extends FindExactlyOnePlugin<AuthTokenDocument>,
10
+ FindOneOrNonePlugin<AuthTokenDocument> {
11
+ consume: (
12
+ this: AuthTokenModel,
13
+ token: string,
14
+ type: AuthTokenType
15
+ ) => Promise<AuthTokenDocument | null>;
16
+ invalidateUnusedFor: (
17
+ this: AuthTokenModel,
18
+ user: {_id: {toString(): string}},
19
+ type: AuthTokenType
20
+ ) => Promise<void>;
21
+ issueFor: (
22
+ this: AuthTokenModel,
23
+ user: {_id: {toString(): string}},
24
+ type: AuthTokenType
25
+ ) => Promise<{authToken: AuthTokenDocument; token: string}>;
26
+ }
27
+
28
+ export interface AuthTokenModel
29
+ extends mongoose.Model<AuthTokenDocument, object, AuthTokenMethods>,
30
+ AuthTokenStatics {}
31
+
32
+ export type AuthTokenSchema = mongoose.Schema<AuthTokenDocument, AuthTokenModel, AuthTokenMethods>;
33
+
34
+ export interface AuthTokenDocument extends mongoose.Document {
35
+ _id: mongoose.Types.ObjectId;
36
+ userId: mongoose.Types.ObjectId;
37
+ tokenHash: string;
38
+ type: AuthTokenType;
39
+ expiresAt: Date;
40
+ consumedAt?: Date;
41
+ created: Date;
42
+ updated: Date;
43
+ }
@@ -0,0 +1,54 @@
1
+ import type mongoose from "mongoose";
2
+ import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "../plugins";
3
+
4
+ export interface McpServiceTokenIssueOptions {
5
+ expiresAt?: Date;
6
+ name: string;
7
+ }
8
+
9
+ export interface McpServiceTokenMethods {
10
+ deleteOne: (this: McpServiceTokenDocument) => Promise<McpServiceTokenDocument>;
11
+ }
12
+
13
+ export interface McpServiceTokenStatics
14
+ extends FindExactlyOnePlugin<McpServiceTokenDocument>,
15
+ FindOneOrNonePlugin<McpServiceTokenDocument> {
16
+ countActiveForUser: (
17
+ this: McpServiceTokenModel,
18
+ userId: mongoose.Types.ObjectId
19
+ ) => Promise<number>;
20
+ issueFor: (
21
+ this: McpServiceTokenModel,
22
+ user: {_id: {toString(): string}},
23
+ options: McpServiceTokenIssueOptions
24
+ ) => Promise<{mcpServiceToken: McpServiceTokenDocument; token: string}>;
25
+ revokeForUser: (
26
+ this: McpServiceTokenModel,
27
+ user: {_id: {toString(): string}},
28
+ tokenId: mongoose.Types.ObjectId
29
+ ) => Promise<McpServiceTokenDocument | null>;
30
+ verify: (this: McpServiceTokenModel, token: string) => Promise<McpServiceTokenDocument | null>;
31
+ }
32
+
33
+ export interface McpServiceTokenModel
34
+ extends mongoose.Model<McpServiceTokenDocument, object, McpServiceTokenMethods>,
35
+ McpServiceTokenStatics {}
36
+
37
+ export type McpServiceTokenSchema = mongoose.Schema<
38
+ McpServiceTokenDocument,
39
+ McpServiceTokenModel,
40
+ McpServiceTokenMethods
41
+ >;
42
+
43
+ export interface McpServiceTokenDocument extends mongoose.Document {
44
+ _id: mongoose.Types.ObjectId;
45
+ created: Date;
46
+ expiresAt?: Date;
47
+ lastUsedAt?: Date;
48
+ name: string;
49
+ revokedAt?: Date;
50
+ tokenHash: string;
51
+ tokenPrefix: string;
52
+ updated: Date;
53
+ userId: mongoose.Types.ObjectId;
54
+ }
@@ -0,0 +1,22 @@
1
+ import {describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type {Request} from "express";
4
+
5
+ import {headerValue} from "./headerValue";
6
+
7
+ describe("headerValue", () => {
8
+ it("returns the first value when the header is an array", () => {
9
+ const req = {headers: {"x-sig": ["first", "second"]}} as unknown as Request;
10
+ assert.equal(headerValue(req, "X-Sig"), "first");
11
+ });
12
+
13
+ it("returns a string header", () => {
14
+ const req = {headers: {"x-sig": "abc"}} as unknown as Request;
15
+ assert.equal(headerValue(req, "X-Sig"), "abc");
16
+ });
17
+
18
+ it("returns undefined when the header is missing", () => {
19
+ const req = {headers: {}} as unknown as Request;
20
+ assert.isUndefined(headerValue(req, "X-Sig"));
21
+ });
22
+ });
@@ -0,0 +1,12 @@
1
+ import type {Request} from "express";
2
+
3
+ export const headerValue = (req: Request, header: string): string | undefined => {
4
+ const raw = req.headers[header.toLowerCase()];
5
+ if (Array.isArray(raw)) {
6
+ return raw[0];
7
+ }
8
+ if (typeof raw === "string") {
9
+ return raw;
10
+ }
11
+ return undefined;
12
+ };
@@ -0,0 +1,34 @@
1
+ export type WebhookClaimResult = "claimed" | "duplicate";
2
+
3
+ export interface WebhookClaimArgs {
4
+ eventId: string;
5
+ source: string;
6
+ }
7
+
8
+ export interface WebhookIdempotencyStore {
9
+ claim: (args: WebhookClaimArgs) => Promise<WebhookClaimResult>;
10
+ release: (args: WebhookClaimArgs) => Promise<void>;
11
+ }
12
+
13
+ const claimKey = ({source, eventId}: WebhookClaimArgs): string => {
14
+ return `${source}\0${eventId}`;
15
+ };
16
+
17
+ export const createMemoryIdempotencyStore = (): WebhookIdempotencyStore => {
18
+ const claimed = new Set<string>();
19
+
20
+ const claim = async (args: WebhookClaimArgs): Promise<WebhookClaimResult> => {
21
+ const key = claimKey(args);
22
+ if (claimed.has(key)) {
23
+ return "duplicate";
24
+ }
25
+ claimed.add(key);
26
+ return "claimed";
27
+ };
28
+
29
+ const release = async (args: WebhookClaimArgs): Promise<void> => {
30
+ claimed.delete(claimKey(args));
31
+ };
32
+
33
+ return {claim, release};
34
+ };
@@ -0,0 +1,274 @@
1
+ import {beforeEach, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type {Application} from "express";
4
+ import mongoose from "mongoose";
5
+ import supertest from "supertest";
6
+
7
+ import type {UserModel as AuthUserModel} from "../../auth";
8
+ import {TerrenoApp} from "../../terrenoApp";
9
+ import {setupTestData, UserModel} from "../../tests";
10
+ import {hmacSignature} from "../verifiers/hmac";
11
+ import {WebhooksApp} from "../webhooksApp";
12
+ import {createMongoIdempotencyStore} from "./mongoStore";
13
+ import {
14
+ DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS,
15
+ getWebhookReceiptModel,
16
+ WEBHOOK_RECEIPTS_COLLECTION,
17
+ } from "./webhookReceipt";
18
+
19
+ const WEBHOOK_SECRET = "whsec_test";
20
+ const FIXTURE_BODY = `{"id":"evt_1"}`;
21
+ const FIXTURE_HMAC_HEX = "030fa3b2413d1993c551364bd53bb9b3edb5c0c34d55dba6ada6041245632811";
22
+
23
+ const buildApp = ({
24
+ handler,
25
+ source = "example",
26
+ }: {
27
+ handler: () => void;
28
+ source?: string;
29
+ }): Application => {
30
+ const webhooks = new WebhooksApp({idempotency: {store: "mongo"}});
31
+ webhooks.route({
32
+ eventId: (req) => String((req.body as {id?: string})?.id ?? ""),
33
+ handler,
34
+ path: "/webhooks/example",
35
+ source,
36
+ verify: hmacSignature({header: "X-Webhook-Signature", secret: WEBHOOK_SECRET}),
37
+ });
38
+ return new TerrenoApp({
39
+ logRequests: false,
40
+ skipListen: true,
41
+ userModel: UserModel as unknown as AuthUserModel,
42
+ })
43
+ .register(webhooks)
44
+ .build();
45
+ };
46
+
47
+ describe("mongo webhook idempotency store", () => {
48
+ beforeEach(async () => {
49
+ await setupTestData();
50
+ await getWebhookReceiptModel().deleteMany({});
51
+ await getWebhookReceiptModel().syncIndexes();
52
+ });
53
+
54
+ it("returns duplicate: true for the same source and eventId without a second handler call", async () => {
55
+ let handlerCalls = 0;
56
+ const app = buildApp({
57
+ handler: () => {
58
+ handlerCalls += 1;
59
+ },
60
+ });
61
+
62
+ const first = await supertest(app)
63
+ .post("/webhooks/example")
64
+ .set("Content-Type", "application/json")
65
+ .set("X-Webhook-Signature", FIXTURE_HMAC_HEX)
66
+ .send(FIXTURE_BODY);
67
+ const second = await supertest(app)
68
+ .post("/webhooks/example")
69
+ .set("Content-Type", "application/json")
70
+ .set("X-Webhook-Signature", FIXTURE_HMAC_HEX)
71
+ .send(FIXTURE_BODY);
72
+
73
+ assert.equal(first.status, 200);
74
+ assert.equal(second.status, 200);
75
+ assert.equal(second.body.duplicate, true);
76
+ assert.equal(handlerCalls, 1);
77
+ });
78
+
79
+ it("lets two sources share the same event id string", async () => {
80
+ const webhooks = new WebhooksApp({idempotency: {store: "mongo"}});
81
+ let stripeCalls = 0;
82
+ let twilioCalls = 0;
83
+ webhooks.route({
84
+ eventId: () => "shared-id",
85
+ handler: () => {
86
+ stripeCalls += 1;
87
+ },
88
+ path: "/webhooks/stripe",
89
+ source: "stripe",
90
+ verify: () => true,
91
+ });
92
+ webhooks.route({
93
+ eventId: () => "shared-id",
94
+ handler: () => {
95
+ twilioCalls += 1;
96
+ },
97
+ path: "/webhooks/twilio",
98
+ source: "twilio",
99
+ verify: () => true,
100
+ });
101
+ const app = new TerrenoApp({
102
+ logRequests: false,
103
+ skipListen: true,
104
+ userModel: UserModel as unknown as AuthUserModel,
105
+ })
106
+ .register(webhooks)
107
+ .build();
108
+
109
+ const stripeRes = await supertest(app)
110
+ .post("/webhooks/stripe")
111
+ .set("Content-Type", "application/json")
112
+ .send(`{"id":"shared-id"}`);
113
+ const twilioRes = await supertest(app)
114
+ .post("/webhooks/twilio")
115
+ .set("Content-Type", "application/json")
116
+ .send(`{"id":"shared-id"}`);
117
+
118
+ assert.equal(stripeRes.status, 200);
119
+ assert.equal(twilioRes.status, 200);
120
+ assert.equal(stripeCalls, 1);
121
+ assert.equal(twilioCalls, 1);
122
+ });
123
+
124
+ it("releases the mongo claim when the handler throws", async () => {
125
+ let handlerCalls = 0;
126
+ const app = buildApp({
127
+ handler: () => {
128
+ handlerCalls += 1;
129
+ if (handlerCalls === 1) {
130
+ throw new Error("mongo handler exploded");
131
+ }
132
+ },
133
+ });
134
+
135
+ const failed = await supertest(app)
136
+ .post("/webhooks/example")
137
+ .set("Content-Type", "application/json")
138
+ .set("X-Webhook-Signature", FIXTURE_HMAC_HEX)
139
+ .send(FIXTURE_BODY);
140
+ const retried = await supertest(app)
141
+ .post("/webhooks/example")
142
+ .set("Content-Type", "application/json")
143
+ .set("X-Webhook-Signature", FIXTURE_HMAC_HEX)
144
+ .send(FIXTURE_BODY);
145
+
146
+ assert.equal(failed.status, 500);
147
+ assert.equal(retried.status, 200);
148
+ assert.equal(handlerCalls, 2);
149
+ });
150
+
151
+ it("creates a unique compound index and a TTL index on created", async () => {
152
+ await getWebhookReceiptModel().create({eventId: "idx", source: "example"});
153
+ const db = mongoose.connection.db;
154
+ assert.ok(db);
155
+ const indexes = await db.collection(WEBHOOK_RECEIPTS_COLLECTION).indexes();
156
+ const unique = indexes.find((index) => {
157
+ return Boolean(index.unique && index.key.source === 1 && index.key.eventId === 1);
158
+ });
159
+ const ttl = indexes.find((index) => index.key.created === 1);
160
+ assert.ok(unique);
161
+ assert.ok(ttl);
162
+ assert.equal(ttl.expireAfterSeconds, DEFAULT_WEBHOOK_RECEIPT_TTL_DAYS * 86_400);
163
+ });
164
+
165
+ it("does not expose webhookReceipts on a modelRouter path", async () => {
166
+ const app = buildApp({handler: () => undefined});
167
+ const spec = await supertest(app).get("/openapi.json").expect(200);
168
+ const paths = spec.body.paths as Record<string, unknown>;
169
+ assert.isUndefined(paths["/webhookReceipts"]);
170
+ assert.isUndefined(paths["/webhook-receipts"]);
171
+ });
172
+
173
+ it("retries index sync after a transient failure", async () => {
174
+ const model = getWebhookReceiptModel();
175
+ const originalSync = model.syncIndexes.bind(model);
176
+ let syncCalls = 0;
177
+ model.syncIndexes = (async () => {
178
+ syncCalls += 1;
179
+ if (syncCalls === 1) {
180
+ throw new Error("index sync failed");
181
+ }
182
+ return originalSync();
183
+ }) as typeof model.syncIndexes;
184
+ const store = createMongoIdempotencyStore();
185
+ try {
186
+ let firstFailed = false;
187
+ try {
188
+ await store.claim({eventId: "retry-1", source: "example"});
189
+ } catch {
190
+ firstFailed = true;
191
+ }
192
+ assert.isTrue(firstFailed);
193
+ const result = await store.claim({eventId: "retry-1", source: "example"});
194
+ assert.equal(result, "claimed");
195
+ assert.equal(syncCalls, 2);
196
+ } finally {
197
+ model.syncIndexes = originalSync;
198
+ }
199
+ });
200
+
201
+ it("rethrows non-duplicate create errors", async () => {
202
+ const store = createMongoIdempotencyStore();
203
+ const model = getWebhookReceiptModel();
204
+ const originalCreate = model.create.bind(model);
205
+ model.create = (async () => {
206
+ throw new Error("write failed");
207
+ }) as typeof model.create;
208
+ try {
209
+ let failed = false;
210
+ try {
211
+ await store.claim({eventId: "write-fail", source: "example"});
212
+ } catch {
213
+ failed = true;
214
+ }
215
+ assert.isTrue(failed);
216
+ } finally {
217
+ model.create = originalCreate;
218
+ }
219
+ });
220
+
221
+ it("applies idempotency.ttlDays to the created TTL index", async () => {
222
+ const webhooks = new WebhooksApp({idempotency: {store: "mongo", ttlDays: 1}});
223
+ webhooks.route({
224
+ eventId: () => "ttl-custom",
225
+ handler: () => undefined,
226
+ path: "/webhooks/ttl",
227
+ source: "example",
228
+ verify: () => true,
229
+ });
230
+ const app = new TerrenoApp({
231
+ logRequests: false,
232
+ skipListen: true,
233
+ userModel: UserModel as unknown as AuthUserModel,
234
+ })
235
+ .register(webhooks)
236
+ .build();
237
+ await supertest(app).post("/webhooks/ttl").set("Content-Type", "application/json").send("{}");
238
+ const db = mongoose.connection.db;
239
+ assert.ok(db);
240
+ const indexes = await db.collection(WEBHOOK_RECEIPTS_COLLECTION).indexes();
241
+ const ttl = indexes.find((index) => index.key.created === 1);
242
+ assert.ok(ttl);
243
+ assert.equal(ttl.expireAfterSeconds, 86_400);
244
+ });
245
+
246
+ it("throws when ttlDays is not a positive number", (): void => {
247
+ let failed = false;
248
+ try {
249
+ createMongoIdempotencyStore({ttlDays: 0});
250
+ } catch {
251
+ failed = true;
252
+ }
253
+ assert.isTrue(failed);
254
+ });
255
+
256
+ it("throws when mongoose is not connected", async () => {
257
+ const store = createMongoIdempotencyStore();
258
+ const descriptor = Object.getOwnPropertyDescriptor(mongoose.connection, "db");
259
+ Object.defineProperty(mongoose.connection, "db", {configurable: true, value: undefined});
260
+ try {
261
+ let failed = false;
262
+ try {
263
+ await store.claim({eventId: "offline", source: "example"});
264
+ } catch {
265
+ failed = true;
266
+ }
267
+ assert.isTrue(failed);
268
+ } finally {
269
+ if (descriptor) {
270
+ Object.defineProperty(mongoose.connection, "db", descriptor);
271
+ }
272
+ }
273
+ });
274
+ });