@terreno/api 57.1.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 (283) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/adminTypes.d.ts +26 -0
  4. package/dist/api.d.ts +4 -0
  5. package/dist/api.js +12 -24
  6. package/dist/auth.d.ts +23 -10
  7. package/dist/auth.js +97 -32
  8. package/dist/authRecovery.d.ts +5 -0
  9. package/dist/authRecovery.js +350 -0
  10. package/dist/authTokens.d.ts +8 -0
  11. package/dist/authTokens.js +162 -0
  12. package/dist/betterAuth.d.ts +33 -0
  13. package/dist/betterAuthApp.d.ts +4 -0
  14. package/dist/betterAuthApp.js +26 -8
  15. package/dist/betterAuthSetup.d.ts +44 -2
  16. package/dist/betterAuthSetup.js +288 -18
  17. package/dist/collectionRegistry.d.ts +38 -0
  18. package/dist/collectionRegistry.js +72 -0
  19. package/dist/configurationApp.d.ts +11 -2
  20. package/dist/configurationApp.js +2 -4
  21. package/dist/docLoader.js +35 -6
  22. package/dist/expressServer.d.ts +26 -3
  23. package/dist/expressServer.js +79 -11
  24. package/dist/index.d.ts +16 -0
  25. package/dist/index.js +38 -2
  26. package/dist/mcp/auth.d.ts +1 -0
  27. package/dist/mcp/auth.js +47 -25
  28. package/dist/mcp/handlers.d.ts +1 -1
  29. package/dist/mcp/handlers.js +67 -233
  30. package/dist/mcp/query.d.ts +2 -2
  31. package/dist/mcp/registry.d.ts +1 -5
  32. package/dist/mcp/registry.js +31 -20
  33. package/dist/mcp/schemaGenerator.d.ts +2 -7
  34. package/dist/mcp/schemaGenerator.js +41 -116
  35. package/dist/mcp/server.d.ts +1 -0
  36. package/dist/mcp/server.js +1 -0
  37. package/dist/mcp/serviceTokens.d.ts +16 -0
  38. package/dist/mcp/serviceTokens.js +345 -0
  39. package/dist/mcp/types.d.ts +2 -2
  40. package/dist/models/mcpServiceToken.d.ts +3 -0
  41. package/dist/models/mcpServiceToken.js +208 -0
  42. package/dist/openApiBuilder.d.ts +5 -4
  43. package/dist/openApiBuilder.js +61 -8
  44. package/dist/openApiCompat.js +1 -1
  45. package/dist/openApiValidator.js +0 -2
  46. package/dist/plugins.d.ts +14 -1
  47. package/dist/plugins.js +17 -6
  48. package/dist/populate.d.ts +2 -2
  49. package/dist/populate.js +47 -42
  50. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  51. package/dist/rateLimit/applyTrustProxy.js +17 -0
  52. package/dist/rateLimit/createStore.d.ts +2 -0
  53. package/dist/rateLimit/createStore.js +28 -0
  54. package/dist/rateLimit/memoryStore.d.ts +2 -0
  55. package/dist/rateLimit/memoryStore.js +108 -0
  56. package/dist/rateLimit/middleware.d.ts +11 -0
  57. package/dist/rateLimit/middleware.js +110 -0
  58. package/dist/rateLimit/mongoStore.d.ts +3 -0
  59. package/dist/rateLimit/mongoStore.js +122 -0
  60. package/dist/rateLimit/policies.d.ts +14 -0
  61. package/dist/rateLimit/policies.js +151 -0
  62. package/dist/rateLimit/redisStore.d.ts +3 -0
  63. package/dist/rateLimit/redisStore.js +155 -0
  64. package/dist/rateLimit/types.d.ts +54 -0
  65. package/dist/rateLimit/types.js +9 -0
  66. package/dist/rbac/access.js +5 -1
  67. package/dist/rbac/assertAllowed.d.ts +9 -0
  68. package/dist/rbac/assertAllowed.js +182 -0
  69. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  70. package/dist/rbac/modelRouterAccess.js +8 -4
  71. package/dist/rbac/permissionUtils.js +3 -2
  72. package/dist/rbac/resolve.js +5 -4
  73. package/dist/rbac/routes.js +15 -6
  74. package/dist/rbac/statements.d.ts +10 -0
  75. package/dist/rbac/statements.js +13 -2
  76. package/dist/realtime/deprecation.d.ts +12 -0
  77. package/dist/realtime/deprecation.js +32 -0
  78. package/dist/realtime/realtimeApp.d.ts +1 -1
  79. package/dist/realtime/realtimeApp.js +10 -11
  80. package/dist/realtime/registry.d.ts +0 -31
  81. package/dist/realtime/registry.js +44 -31
  82. package/dist/realtime/socketAuth.d.ts +5 -5
  83. package/dist/realtime/socketAuth.js +11 -1
  84. package/dist/realtime/socketUser.d.ts +5 -1
  85. package/dist/realtime/types.d.ts +14 -4
  86. package/dist/schemaMetadata.d.ts +56 -0
  87. package/dist/schemaMetadata.js +513 -0
  88. package/dist/seedRunner.d.ts +88 -0
  89. package/dist/seedRunner.js +627 -0
  90. package/dist/sync/executors.d.ts +12 -2
  91. package/dist/sync/executors.js +8 -10
  92. package/dist/sync/loadHarness.js +28 -19
  93. package/dist/sync/models.js +26 -24
  94. package/dist/sync/mutationHandler.d.ts +9 -0
  95. package/dist/sync/mutationHandler.js +11 -6
  96. package/dist/sync/registrationSideEffects.d.ts +35 -0
  97. package/dist/sync/registrationSideEffects.js +151 -0
  98. package/dist/sync/registry.d.ts +2 -52
  99. package/dist/sync/registry.js +38 -187
  100. package/dist/sync/routes.js +3 -2
  101. package/dist/sync/scripts/compactTombstones.js +0 -2
  102. package/dist/sync/syncApp.d.ts +3 -3
  103. package/dist/sync/syncApp.js +4 -4
  104. package/dist/sync/syncBatch.js +3 -2
  105. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  106. package/dist/sync/syncSeqPlugin.js +20 -16
  107. package/dist/terrenoApp.d.ts +19 -5
  108. package/dist/terrenoApp.js +66 -18
  109. package/dist/tests/models.d.ts +2 -0
  110. package/dist/tests/models.js +6 -0
  111. package/dist/types/authToken.d.ts +33 -0
  112. package/dist/types/authToken.js +2 -0
  113. package/dist/types/mcpServiceToken.d.ts +41 -0
  114. package/dist/types/mcpServiceToken.js +2 -0
  115. package/dist/webhooks/headerValue.d.ts +2 -0
  116. package/dist/webhooks/headerValue.js +14 -0
  117. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  118. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  119. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  120. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  121. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  122. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  123. package/dist/webhooks/rawBody.d.ts +14 -0
  124. package/dist/webhooks/rawBody.js +22 -0
  125. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  126. package/dist/webhooks/timingSafeEqual.js +17 -0
  127. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  128. package/dist/webhooks/verifiers/hmac.js +49 -0
  129. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  130. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  131. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  132. package/dist/webhooks/verifiers/stripe.js +99 -0
  133. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  134. package/dist/webhooks/verifiers/twilio.js +112 -0
  135. package/dist/webhooks/webhooksApp.d.ts +33 -0
  136. package/dist/webhooks/webhooksApp.js +195 -0
  137. package/package.json +5 -6
  138. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  139. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  140. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  141. package/src/actions.ts +20 -13
  142. package/src/adminModelRouter.test.ts +133 -0
  143. package/src/adminTypes.ts +23 -0
  144. package/src/api.arrayOperations.test.ts +43 -31
  145. package/src/api.hooks.test.ts +38 -29
  146. package/src/api.query.test.ts +31 -31
  147. package/src/api.test.ts +95 -96
  148. package/src/api.ts +16 -27
  149. package/src/auth.test.ts +107 -51
  150. package/src/auth.ts +98 -29
  151. package/src/authRecovery.test.ts +281 -0
  152. package/src/authRecovery.ts +279 -0
  153. package/src/authTokens.test.ts +94 -0
  154. package/src/authTokens.ts +118 -0
  155. package/src/authVerification.test.ts +293 -0
  156. package/src/betterAuth.ts +24 -0
  157. package/src/betterAuthApp.test.ts +1 -0
  158. package/src/betterAuthApp.ts +27 -9
  159. package/src/betterAuthSetup.test.ts +568 -38
  160. package/src/betterAuthSetup.ts +260 -5
  161. package/src/collectionRegistry.test.ts +165 -0
  162. package/src/collectionRegistry.ts +115 -0
  163. package/src/configurationApp.ts +13 -7
  164. package/src/docLoader.test.ts +45 -1
  165. package/src/docLoader.ts +37 -6
  166. package/src/express.d.ts +1 -0
  167. package/src/expressServer.test.ts +130 -66
  168. package/src/expressServer.ts +75 -19
  169. package/src/githubAuth.test.ts +60 -55
  170. package/src/index.ts +58 -0
  171. package/src/mcp/auth.test.ts +47 -0
  172. package/src/mcp/auth.ts +32 -11
  173. package/src/mcp/handlers.ts +45 -172
  174. package/src/mcp/integration.test.ts +59 -9
  175. package/src/mcp/query.ts +2 -4
  176. package/src/mcp/registry.ts +29 -20
  177. package/src/mcp/schemaGenerator.test.ts +8 -0
  178. package/src/mcp/schemaGenerator.ts +49 -131
  179. package/src/mcp/server.ts +2 -0
  180. package/src/mcp/serviceTokens.test.ts +330 -0
  181. package/src/mcp/serviceTokens.ts +307 -0
  182. package/src/mcp/toolGenerator.test.ts +1 -1
  183. package/src/mcp/types.ts +2 -6
  184. package/src/models/mcpServiceToken.test.ts +129 -0
  185. package/src/models/mcpServiceToken.ts +158 -0
  186. package/src/openApi.test.ts +80 -64
  187. package/src/openApiBuilder.test.ts +95 -7
  188. package/src/openApiBuilder.ts +46 -9
  189. package/src/openApiCompat.ts +1 -1
  190. package/src/openApiValidator.test.ts +49 -54
  191. package/src/openApiValidator.ts +1 -3
  192. package/src/plugins.test.ts +14 -0
  193. package/src/plugins.ts +34 -9
  194. package/src/populate.test.ts +34 -0
  195. package/src/populate.ts +40 -29
  196. package/src/rateLimit/applyTrustProxy.ts +17 -0
  197. package/src/rateLimit/createStore.ts +25 -0
  198. package/src/rateLimit/memoryStore.ts +40 -0
  199. package/src/rateLimit/middleware.ts +79 -0
  200. package/src/rateLimit/mongoStore.test.ts +80 -0
  201. package/src/rateLimit/mongoStore.ts +76 -0
  202. package/src/rateLimit/policies.ts +130 -0
  203. package/src/rateLimit/rateLimit.test.ts +328 -0
  204. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  205. package/src/rateLimit/redisStore.test.ts +114 -0
  206. package/src/rateLimit/redisStore.ts +85 -0
  207. package/src/rateLimit/types.ts +64 -0
  208. package/src/rbac/access.ts +5 -1
  209. package/src/rbac/assertAllowed.test.ts +325 -0
  210. package/src/rbac/assertAllowed.ts +157 -0
  211. package/src/rbac/backfillAdmins.test.ts +124 -0
  212. package/src/rbac/fieldViews.test.ts +89 -0
  213. package/src/rbac/modelRouterAccess.test.ts +126 -0
  214. package/src/rbac/modelRouterAccess.ts +5 -2
  215. package/src/rbac/permissionUtils.ts +3 -2
  216. package/src/rbac/realtimeAccess.test.ts +109 -1
  217. package/src/rbac/resolve.ts +5 -4
  218. package/src/rbac/roleManager.test.ts +169 -0
  219. package/src/rbac/routes.test.ts +233 -0
  220. package/src/rbac/routes.ts +16 -6
  221. package/src/rbac/statements.test.ts +2 -0
  222. package/src/rbac/statements.ts +12 -1
  223. package/src/realtime/deprecation.test.ts +60 -0
  224. package/src/realtime/deprecation.ts +32 -0
  225. package/src/realtime/realtime.test.ts +8 -4
  226. package/src/realtime/realtimeApp.ts +10 -11
  227. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  228. package/src/realtime/registry.ts +48 -42
  229. package/src/realtime/sessionRevalidation.test.ts +57 -44
  230. package/src/realtime/socketAuth.test.ts +75 -23
  231. package/src/realtime/socketAuth.ts +17 -6
  232. package/src/realtime/socketUser.ts +5 -3
  233. package/src/realtime/types.ts +14 -4
  234. package/src/schemaMetadata.test.ts +405 -0
  235. package/src/schemaMetadata.ts +593 -0
  236. package/src/scrubAdminFields.test.ts +105 -0
  237. package/src/seedRunner.test.ts +591 -0
  238. package/src/seedRunner.ts +464 -0
  239. package/src/sync/docMatchesMutationData.test.ts +16 -0
  240. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  241. package/src/sync/executors.test.ts +40 -0
  242. package/src/sync/executors.ts +24 -12
  243. package/src/sync/integration.test.ts +15 -7
  244. package/src/sync/loadHarness.ts +28 -19
  245. package/src/sync/models.ts +32 -18
  246. package/src/sync/mutationHandler.test.ts +16 -16
  247. package/src/sync/mutationHandler.ts +9 -7
  248. package/src/sync/registrationSideEffects.test.ts +126 -0
  249. package/src/sync/registrationSideEffects.ts +131 -0
  250. package/src/sync/registry.ts +45 -171
  251. package/src/sync/routes.ts +3 -2
  252. package/src/sync/scripts/compactTombstones.ts +0 -2
  253. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  254. package/src/sync/sync.test.ts +25 -23
  255. package/src/sync/syncApp.ts +4 -4
  256. package/src/sync/syncBatch.ts +3 -2
  257. package/src/sync/syncFrontier.test.ts +17 -15
  258. package/src/sync/syncPhaseC.test.ts +54 -43
  259. package/src/sync/syncRoutes.test.ts +51 -36
  260. package/src/sync/syncSeqPlugin.ts +66 -44
  261. package/src/sync/syncSocket.test.ts +112 -81
  262. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  263. package/src/terrenoApp.ts +87 -15
  264. package/src/tests/models.ts +14 -1
  265. package/src/types/authToken.ts +43 -0
  266. package/src/types/mcpServiceToken.ts +54 -0
  267. package/src/webhooks/headerValue.test.ts +22 -0
  268. package/src/webhooks/headerValue.ts +12 -0
  269. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  270. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  271. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  272. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  273. package/src/webhooks/rawBody.test.ts +74 -0
  274. package/src/webhooks/rawBody.ts +23 -0
  275. package/src/webhooks/timingSafeEqual.ts +16 -0
  276. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  277. package/src/webhooks/verifiers/hmac.ts +54 -0
  278. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  279. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  280. package/src/webhooks/verifiers/stripe.ts +67 -0
  281. package/src/webhooks/verifiers/twilio.ts +69 -0
  282. package/src/webhooks/webhooksApp.test.ts +221 -0
  283. package/src/webhooks/webhooksApp.ts +144 -0
@@ -1,8 +1,6 @@
1
- // noExplicitAny: test mock typing
2
- // biome-ignore-all lint/suspicious/noExplicitAny: test mock typing
3
1
  import {afterEach, beforeEach, describe, expect, it, setSystemTime} from "bun:test";
4
2
  import type express from "express";
5
- import mongoose, {model, Schema} from "mongoose";
3
+ import mongoose, {type Model, model, Schema} from "mongoose";
6
4
  import passport from "passport";
7
5
  import passportLocalMongoose from "passport-local-mongoose";
8
6
  import supertest from "supertest";
@@ -72,22 +70,26 @@ const testUserSchema = new Schema<TestUser>({
72
70
  username: {description: "The user's username", type: String},
73
71
  });
74
72
 
75
- testUserSchema.plugin(passportLocalMongoose as any, {
76
- attemptsField: "attempts",
77
- interval: 1,
78
- limitAttempts: true,
79
- maxAttempts: 3,
80
- maxInterval: 1,
81
- usernameCaseInsensitive: true,
82
- usernameField: "email",
83
- });
73
+ testUserSchema.plugin(
74
+ passportLocalMongoose as unknown as (schema: Schema, options?: Record<string, unknown>) => void,
75
+ {
76
+ attemptsField: "attempts",
77
+ interval: 1,
78
+ limitAttempts: true,
79
+ maxAttempts: 3,
80
+ maxInterval: 1,
81
+ usernameCaseInsensitive: true,
82
+ usernameField: "email",
83
+ }
84
+ );
84
85
  testUserSchema.plugin(createdUpdatedPlugin);
85
86
  testUserSchema.plugin(isDisabledPlugin);
86
87
  testUserSchema.plugin(githubUserPlugin);
87
88
 
88
89
  // Get or create model to avoid model redefinition errors
89
90
  const GitHubTestUserModel =
90
- mongoose.models.GitHubTestUser || model<TestUser>("GitHubTestUser", testUserSchema);
91
+ (mongoose.models.GitHubTestUser as Model<TestUser> | undefined) ??
92
+ model<TestUser>("GitHubTestUser", testUserSchema);
91
93
 
92
94
  // Connect to database before tests
93
95
  const connectDb = async () => {
@@ -114,9 +116,9 @@ describe("githubUserPlugin", () => {
114
116
 
115
117
  it("githubId is indexed and sparse", () => {
116
118
  const githubIdPath = testUserSchema.path("githubId");
117
- expect((githubIdPath as any).options.index).toBe(true);
118
- expect((githubIdPath as any).options.sparse).toBe(true);
119
- expect((githubIdPath as any).options.unique).toBe(true);
119
+ expect(githubIdPath.options.index).toBe(true);
120
+ expect(githubIdPath.options.sparse).toBe(true);
121
+ expect(githubIdPath.options.unique).toBe(true);
120
122
  });
121
123
  });
122
124
 
@@ -136,7 +138,7 @@ describe("GitHub auth routes", () => {
136
138
  email: "test@example.com",
137
139
  name: "Test User",
138
140
  });
139
- await (testUser as any).setPassword("password123");
141
+ await (testUser as unknown as PasswordedDocument).setPassword("password123");
140
142
  await testUser.save();
141
143
 
142
144
  function addRoutes(router: express.Router): void {
@@ -152,7 +154,7 @@ describe("GitHub auth routes", () => {
152
154
  clientSecret: "test-client-secret",
153
155
  },
154
156
  skipListen: true,
155
- userModel: GitHubTestUserModel as any,
157
+ userModel: GitHubTestUserModel as unknown as UserModel,
156
158
  }).build();
157
159
  agent = supertest.agent(app);
158
160
  });
@@ -187,8 +189,8 @@ describe("GitHub auth routes", () => {
187
189
  // Link github to this user
188
190
  const user = await GitHubTestUserModel.findOne({email: "test@example.com"});
189
191
  if (user) {
190
- (user as any).githubId = "99999";
191
- (user as any).githubUsername = "testghuser";
192
+ user.githubId = "99999";
193
+ user.githubUsername = "testghuser";
192
194
  await user.save();
193
195
  }
194
196
 
@@ -202,8 +204,8 @@ describe("GitHub auth routes", () => {
202
204
 
203
205
  // Verify github fields are cleared
204
206
  const updatedUser = await GitHubTestUserModel.findOne({email: "test@example.com"});
205
- expect((updatedUser as any).githubId).toBeUndefined();
206
- expect((updatedUser as any).githubUsername).toBeUndefined();
207
+ expect(updatedUser?.githubId).toBeUndefined();
208
+ expect(updatedUser?.githubUsername).toBeUndefined();
207
209
  });
208
210
 
209
211
  it("user can have both password and GitHub auth", async () => {
@@ -214,8 +216,8 @@ describe("GitHub auth routes", () => {
214
216
  }
215
217
 
216
218
  // Link GitHub
217
- (user as any).githubId = "88888";
218
- (user as any).githubUsername = "linkeduser";
219
+ user.githubId = "88888";
220
+ user.githubUsername = "linkeduser";
219
221
  await user.save();
220
222
 
221
223
  // Can still login with password
@@ -230,8 +232,8 @@ describe("GitHub auth routes", () => {
230
232
  // and we verify GitHub fields are set
231
233
  const updatedUser = await GitHubTestUserModel.findOne({email: "test@example.com"});
232
234
  expect(updatedUser).toBeDefined();
233
- expect((updatedUser as any).githubId).toBe("88888");
234
- expect((updatedUser as any).githubUsername).toBe("linkeduser");
235
+ expect(updatedUser?.githubId).toBe("88888");
236
+ expect(updatedUser?.githubUsername).toBe("linkeduser");
235
237
  });
236
238
  });
237
239
 
@@ -253,7 +255,7 @@ describe("GitHub auth disabled", () => {
253
255
  app = new TerrenoApp({
254
256
  configureApp: addRoutes,
255
257
  skipListen: true,
256
- userModel: GitHubTestUserModel as any,
258
+ userModel: GitHubTestUserModel as unknown as UserModel,
257
259
  }).build();
258
260
  agent = supertest.agent(app);
259
261
  });
@@ -282,7 +284,10 @@ interface VerifyError {
282
284
  message?: string;
283
285
  }
284
286
 
285
- type VerifiedUser = any;
287
+ type VerifiedUser = {
288
+ _id: mongoose.Types.ObjectId | string;
289
+ email?: string;
290
+ } & Partial<GitHubUserFields>;
286
291
 
287
292
  interface VerifyStrategy {
288
293
  _verify: (
@@ -316,7 +321,7 @@ const invokeGitHubVerify = (
316
321
  };
317
322
 
318
323
  describe("GitHub strategy verify callback", () => {
319
- const testApp = {get: () => {}, use: () => {}} as any;
324
+ const testApp = {get: () => {}, use: () => {}} as unknown as express.Application;
320
325
 
321
326
  beforeEach(async () => {
322
327
  await connectDb();
@@ -325,7 +330,7 @@ describe("GitHub strategy verify callback", () => {
325
330
 
326
331
  it("uses custom findOrCreateUser when provided", async () => {
327
332
  const customUser = {_id: "custom-user-id", email: "custom@example.com"};
328
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
333
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
329
334
  callbackURL: "http://localhost:9000/auth/github/callback",
330
335
  clientId: "id",
331
336
  clientSecret: "secret",
@@ -338,7 +343,7 @@ describe("GitHub strategy verify callback", () => {
338
343
  });
339
344
 
340
345
  it("creates a new user when no existing GitHub or email user", async () => {
341
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
346
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
342
347
  callbackURL: "http://localhost:9000/auth/github/callback",
343
348
  clientId: "id",
344
349
  clientSecret: "secret",
@@ -366,9 +371,9 @@ describe("GitHub strategy verify callback", () => {
366
371
  githubId: "gh-existing-1",
367
372
  githubUsername: "ghuser",
368
373
  name: "GH User",
369
- } as any);
374
+ });
370
375
 
371
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
376
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
372
377
  callbackURL: "http://localhost:9000/auth/github/callback",
373
378
  clientId: "id",
374
379
  clientSecret: "secret",
@@ -379,16 +384,16 @@ describe("GitHub strategy verify callback", () => {
379
384
  username: "ghuser",
380
385
  });
381
386
  expect(result.err).toBeNull();
382
- expect(result.user._id.toString()).toBe((existingUser as any)._id.toString());
387
+ expect(result.user._id.toString()).toBe(existingUser._id.toString());
383
388
  });
384
389
 
385
390
  it("links GitHub to authenticated user when allowAccountLinking=true", async () => {
386
391
  const existingUser = await GitHubTestUserModel.create({
387
392
  email: "link@example.com",
388
393
  name: "Link User",
389
- } as any);
394
+ });
390
395
 
391
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
396
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
392
397
  allowAccountLinking: true,
393
398
  callbackURL: "http://localhost:9000/auth/github/callback",
394
399
  clientId: "id",
@@ -410,9 +415,9 @@ describe("GitHub strategy verify callback", () => {
410
415
  it("rejects linking when allowAccountLinking=false", async () => {
411
416
  const existingUser = await GitHubTestUserModel.create({
412
417
  email: "nolink@example.com",
413
- } as any);
418
+ });
414
419
 
415
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
420
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
416
421
  allowAccountLinking: false,
417
422
  callbackURL: "http://localhost:9000/auth/github/callback",
418
423
  clientId: "id",
@@ -422,19 +427,19 @@ describe("GitHub strategy verify callback", () => {
422
427
  const req = {user: existingUser};
423
428
  const result = await invokeGitHubVerify(req, "access", "refresh", {id: "gh-nolink-1"});
424
429
  expect(result.err).toBeDefined();
425
- expect((result.err as any).status).toBe(400);
430
+ expect(result.err?.status).toBe(400);
426
431
  });
427
432
 
428
433
  it("rejects linking when GitHub account belongs to another user", async () => {
429
434
  const userA = await GitHubTestUserModel.create({
430
435
  email: "a@example.com",
431
- } as any);
436
+ });
432
437
  await GitHubTestUserModel.create({
433
438
  email: "b@example.com",
434
439
  githubId: "gh-other-1",
435
- } as any);
440
+ });
436
441
 
437
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
442
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
438
443
  allowAccountLinking: true,
439
444
  callbackURL: "http://localhost:9000/auth/github/callback",
440
445
  clientId: "id",
@@ -444,15 +449,15 @@ describe("GitHub strategy verify callback", () => {
444
449
  const req = {user: userA};
445
450
  const result = await invokeGitHubVerify(req, "access", "refresh", {id: "gh-other-1"});
446
451
  expect(result.err).toBeDefined();
447
- expect((result.err as any).status).toBe(400);
452
+ expect(result.err?.status).toBe(400);
448
453
  });
449
454
 
450
455
  it("links GitHub to existing email user when allowAccountLinking is not false", async () => {
451
456
  await GitHubTestUserModel.create({
452
457
  email: "emailuser@example.com",
453
- } as any);
458
+ });
454
459
 
455
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
460
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
456
461
  callbackURL: "http://localhost:9000/auth/github/callback",
457
462
  clientId: "id",
458
463
  clientSecret: "secret",
@@ -471,9 +476,9 @@ describe("GitHub strategy verify callback", () => {
471
476
  it("rejects email-link when allowAccountLinking=false", async () => {
472
477
  await GitHubTestUserModel.create({
473
478
  email: "emailnolink@example.com",
474
- } as any);
479
+ });
475
480
 
476
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
481
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
477
482
  allowAccountLinking: false,
478
483
  callbackURL: "http://localhost:9000/auth/github/callback",
479
484
  clientId: "id",
@@ -485,12 +490,12 @@ describe("GitHub strategy verify callback", () => {
485
490
  id: "gh-email-nolink-1",
486
491
  });
487
492
  expect(result.err).toBeDefined();
488
- expect((result.err as any).status).toBe(400);
493
+ expect(result.err?.status).toBe(400);
489
494
  });
490
495
 
491
496
  it("returns error when thrown during lookup", async () => {
492
497
  // Set up strategy with findOrCreateUser that throws
493
- setupGitHubAuth(testApp, GitHubTestUserModel as any, {
498
+ setupGitHubAuth(testApp, GitHubTestUserModel as unknown as UserModel, {
494
499
  callbackURL: "http://localhost:9000/auth/github/callback",
495
500
  clientId: "id",
496
501
  clientSecret: "secret",
@@ -527,7 +532,7 @@ describe("addGitHubAuthRoutes link endpoints", () => {
527
532
  clientSecret: "test-client-secret",
528
533
  },
529
534
  skipListen: true,
530
- userModel: GitHubTestUserModel as any,
535
+ userModel: GitHubTestUserModel as unknown as UserModel,
531
536
  }).build();
532
537
  agent = supertest.agent(app);
533
538
  });
@@ -553,8 +558,8 @@ describe("addGitHubAuthRoutes link endpoints", () => {
553
558
  githubId: "77777",
554
559
  githubProfileUrl: "http://profile",
555
560
  githubUsername: "ghunlink",
556
- } as any);
557
- await (user as any).setPassword("password123");
561
+ });
562
+ await (user as unknown as PasswordedDocument).setPassword("password123");
558
563
  await user.save();
559
564
 
560
565
  const loginRes = await agent
@@ -568,9 +573,9 @@ describe("addGitHubAuthRoutes link endpoints", () => {
568
573
  .expect(200);
569
574
 
570
575
  const updatedUser = await GitHubTestUserModel.findOne({email: "unlinkme@example.com"});
571
- expect((updatedUser as any).githubId).toBeUndefined();
572
- expect((updatedUser as any).githubAvatarUrl).toBeUndefined();
573
- expect((updatedUser as any).githubProfileUrl).toBeUndefined();
576
+ expect(updatedUser?.githubId).toBeUndefined();
577
+ expect(updatedUser?.githubAvatarUrl).toBeUndefined();
578
+ expect(updatedUser?.githubProfileUrl).toBeUndefined();
574
579
  });
575
580
  });
576
581
 
package/src/index.ts CHANGED
@@ -2,6 +2,8 @@ export * from "./actions";
2
2
  export * from "./adminTypes";
3
3
  export * from "./api";
4
4
  export * from "./auth";
5
+ export * from "./authRecovery";
6
+ export * from "./authTokens";
5
7
  export * from "./betterAuth";
6
8
  export * from "./betterAuthApp";
7
9
  export * from "./betterAuthSetup";
@@ -26,6 +28,13 @@ export {
26
28
  } from "./mcp/registry";
27
29
  export {generateInputSchema, generateToolDescription} from "./mcp/schemaGenerator";
28
30
  export {type MCPServerOptions, mountMCPServer} from "./mcp/server";
31
+ export {
32
+ addMcpServiceTokenRoutes,
33
+ MAX_ACTIVE_MCP_SERVICE_TOKENS,
34
+ type McpServiceTokenRoutesOptions,
35
+ type McpServiceTokensAppOption,
36
+ resolveMcpServiceTokensOption,
37
+ } from "./mcp/serviceTokens";
29
38
  export {
30
39
  generateAllTools,
31
40
  generateToolsForEntry,
@@ -43,6 +52,7 @@ export type {
43
52
  export * from "./middleware";
44
53
  export * from "./models/consentForm";
45
54
  export * from "./models/consentResponse";
55
+ export * from "./models/mcpServiceToken";
46
56
  export * from "./models/versionConfig";
47
57
  export * from "./notifiers/googleChatNotifier";
48
58
  export * from "./notifiers/slackNotifier";
@@ -54,7 +64,19 @@ export * from "./openApiValidator";
54
64
  export * from "./permissions";
55
65
  export * from "./plugins";
56
66
  export * from "./populate";
67
+ export type {
68
+ RateLimitLimits,
69
+ RateLimitOptions,
70
+ RateLimitRedisClient,
71
+ RateLimitStore,
72
+ } from "./rateLimit/types";
73
+ export {
74
+ DEFAULT_API_MAX,
75
+ DEFAULT_AUTH_MAX,
76
+ DEFAULT_WINDOW_MS,
77
+ } from "./rateLimit/types";
57
78
  export * from "./rbac/access";
79
+ export {assertAllowed} from "./rbac/assertAllowed";
58
80
  export {
59
81
  createRbacAuditModel,
60
82
  type RbacAuditDocument,
@@ -150,9 +172,26 @@ export type {
150
172
  RealtimeEvent,
151
173
  } from "./realtime/types";
152
174
  export * from "./requestContext";
175
+ export {
176
+ type DescribeModelForRouterOptions,
177
+ type DescribeModelOptions,
178
+ describeModel,
179
+ describeModelForRouter,
180
+ type FieldDescription,
181
+ type FieldKind,
182
+ fieldDescriptionToAdminMeta,
183
+ fieldDescriptionToOpenApiProperty,
184
+ fieldDescriptionToZodType,
185
+ type ModelDescription,
186
+ modelDescriptionToAdminFields,
187
+ modelDescriptionToOpenApiSpec,
188
+ nestDottedFieldDescriptions,
189
+ SYSTEM_FIELD_PATHS,
190
+ } from "./schemaMetadata";
153
191
  export * from "./scriptRunner";
154
192
  export {adminBodyFieldsToStrip, scrubAdminFields, stripAdminBodyFields} from "./scrubAdminFields";
155
193
  export * from "./secretProviders";
194
+ export * from "./seedRunner";
156
195
  export * from "./sync/executors";
157
196
  export * from "./sync/models";
158
197
  export * from "./sync/mutationHandler";
@@ -174,4 +213,23 @@ export * from "./types/consentForm";
174
213
  export * from "./types/consentResponse";
175
214
  export * from "./utils";
176
215
  export * from "./versionCheckPlugin";
216
+ export type {
217
+ WebhookClaimArgs,
218
+ WebhookClaimResult,
219
+ WebhookIdempotencyStore,
220
+ } from "./webhooks/idempotency/memoryStore";
221
+ export {createMemoryIdempotencyStore} from "./webhooks/idempotency/memoryStore";
222
+ export {type HmacSignatureOptions, hmacSignature} from "./webhooks/verifiers/hmac";
223
+ export {
224
+ type SendgridEventSignatureOptions,
225
+ sendgridEventSignature,
226
+ } from "./webhooks/verifiers/sendgrid";
227
+ export {type StripeSignatureOptions, stripeSignature} from "./webhooks/verifiers/stripe";
228
+ export {type TwilioSignatureOptions, twilioSignature} from "./webhooks/verifiers/twilio";
229
+ export {
230
+ type WebhookHandlerContext,
231
+ type WebhookRouteOptions,
232
+ WebhooksApp,
233
+ type WebhooksAppOptions,
234
+ } from "./webhooks/webhooksApp";
177
235
  export {z} from "./zodOpenApi";
@@ -1,9 +1,11 @@
1
1
  import {beforeEach, describe, expect, it} from "bun:test";
2
+ import {assert} from "chai";
2
3
  import jwt from "jsonwebtoken";
3
4
  import mongoose, {Schema} from "mongoose";
4
5
 
5
6
  import type {UserModel} from "../auth";
6
7
  import type {BetterAuthInstance} from "../betterAuthSetup";
8
+ import {McpServiceToken} from "../models/mcpServiceToken";
7
9
  import {findOneOrNone} from "../plugins";
8
10
  import {extractUserFromHeaders} from "./auth";
9
11
 
@@ -46,6 +48,7 @@ const signToken = (payload: Record<string, unknown>, secret = "test-token-secret
46
48
  describe("extractUserFromHeaders", () => {
47
49
  beforeEach(async () => {
48
50
  await UserTestModel.deleteMany({});
51
+ await McpServiceToken.deleteMany({});
49
52
  process.env.TOKEN_SECRET = "test-token-secret";
50
53
  });
51
54
 
@@ -70,6 +73,50 @@ describe("extractUserFromHeaders", () => {
70
73
  expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
71
74
  });
72
75
 
76
+ it("resolves the owner of an active MCP service token before JWT verification", async () => {
77
+ const created = await UserTestModel.create({email: "mcp-token@example.com"});
78
+ const issued = await McpServiceToken.issueFor({_id: created._id}, {name: "Perplexity"});
79
+
80
+ const user = await extractUserFromHeaders(
81
+ {authorization: `Bearer ${issued.token}`},
82
+ {mcpServiceTokens: true, userModel}
83
+ );
84
+
85
+ assert.equal(String((user as unknown as MCPAuthUserFields)?._id), created._id.toString());
86
+
87
+ await Bun.sleep(10);
88
+ const usedToken = await McpServiceToken.findById(issued.mcpServiceToken._id);
89
+ assert.isDefined(usedToken?.lastUsedAt);
90
+ });
91
+
92
+ it("rejects revoked MCP service tokens", async () => {
93
+ const created = await UserTestModel.create({email: "revoked-mcp-token@example.com"});
94
+ const issued = await McpServiceToken.issueFor({_id: created._id}, {name: "Revoked"});
95
+ await McpServiceToken.revokeForUser({_id: created._id}, issued.mcpServiceToken._id);
96
+
97
+ const user = await extractUserFromHeaders(
98
+ {authorization: `Bearer ${issued.token}`},
99
+ {mcpServiceTokens: true, userModel}
100
+ );
101
+
102
+ assert.isUndefined(user);
103
+ });
104
+
105
+ it("rejects MCP service tokens belonging to disabled users", async () => {
106
+ const created = await UserTestModel.create({
107
+ disabled: true,
108
+ email: "disabled-mcp-token@example.com",
109
+ });
110
+ const issued = await McpServiceToken.issueFor({_id: created._id}, {name: "Disabled"});
111
+
112
+ const user = await extractUserFromHeaders(
113
+ {authorization: `Bearer ${issued.token}`},
114
+ {mcpServiceTokens: true, userModel}
115
+ );
116
+
117
+ assert.isUndefined(user);
118
+ });
119
+
73
120
  it("accepts a raw token without the Bearer prefix", async () => {
74
121
  const created = await UserTestModel.create({email: "raw@example.com"});
75
122
  const token = signToken({sub: created._id.toString()});
package/src/mcp/auth.ts CHANGED
@@ -1,13 +1,16 @@
1
1
  import jwt from "jsonwebtoken";
2
+ import {DateTime} from "luxon";
2
3
 
3
4
  import type {User, UserModel} from "../auth";
4
5
  import type {BetterAuthInstance} from "../betterAuthSetup";
5
6
  import {logger} from "../logger";
7
+ import {McpServiceToken} from "../models/mcpServiceToken";
6
8
  import {findOneOrNoneFor} from "../plugins";
7
9
 
8
10
  export interface MCPAuthContext {
9
11
  userModel: UserModel;
10
12
  betterAuth?: BetterAuthInstance;
13
+ mcpServiceTokens?: boolean;
11
14
  }
12
15
 
13
16
  /**
@@ -34,9 +37,36 @@ export const extractUserFromHeaders = async (
34
37
  headers: Record<string, string | string[] | undefined>,
35
38
  context: MCPAuthContext
36
39
  ): Promise<User | undefined> => {
37
- const {userModel, betterAuth} = context;
40
+ const {userModel, betterAuth, mcpServiceTokens} = context;
41
+ const authorization =
42
+ typeof headers.authorization === "string"
43
+ ? headers.authorization
44
+ : Array.isArray(headers.authorization)
45
+ ? headers.authorization[0]
46
+ : undefined;
47
+ const token = authorization?.startsWith("Bearer ") ? authorization.slice(7) : authorization;
48
+
49
+ // Resolve MCP service tokens before session/JWT auth because mcp_ is a distinct credential type.
50
+ if (mcpServiceTokens && token?.startsWith("mcp_")) {
51
+ const serviceToken = await McpServiceToken.verify(token);
52
+ if (!serviceToken) {
53
+ return undefined;
54
+ }
55
+ const user = await userModel.findById(serviceToken.userId);
56
+ const activeUser = rejectIfDisabled(user as unknown as User | undefined, "MCP service token");
57
+ if (!activeUser) {
58
+ return undefined;
59
+ }
60
+ void McpServiceToken.updateOne(
61
+ {_id: serviceToken._id},
62
+ {$set: {lastUsedAt: DateTime.now().toJSDate()}}
63
+ ).catch((error) => {
64
+ logger.debug(`MCP service token last-used update failed: ${error}`);
65
+ });
66
+ return activeUser;
67
+ }
38
68
 
39
- // Try Better Auth first if configured
69
+ // Try Better Auth first if configured.
40
70
  if (betterAuth) {
41
71
  try {
42
72
  const session = await betterAuth.api.getSession({
@@ -58,19 +88,10 @@ export const extractUserFromHeaders = async (
58
88
  }
59
89
 
60
90
  // Try JWT auth
61
- const authorization =
62
- typeof headers.authorization === "string"
63
- ? headers.authorization
64
- : Array.isArray(headers.authorization)
65
- ? headers.authorization[0]
66
- : undefined;
67
-
68
91
  if (!authorization) {
69
92
  return undefined;
70
93
  }
71
94
 
72
- const token = authorization.startsWith("Bearer ") ? authorization.slice(7) : authorization;
73
-
74
95
  if (!token) {
75
96
  return undefined;
76
97
  }