@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
@@ -0,0 +1,307 @@
1
+ import type {Application, NextFunction, Request, Response} from "express";
2
+ import {DateTime} from "luxon";
3
+ import mongoose from "mongoose";
4
+
5
+ import {asyncHandler, type OpenApiMiddleware} from "../api";
6
+ import {authenticateMiddleware, type User} from "../auth";
7
+ import {BadRequestError, NotFoundError, UnauthorizedError} from "../errors";
8
+ import {McpServiceToken} from "../models/mcpServiceToken";
9
+ import {createOpenApiBuilder} from "../openApiBuilder";
10
+ import type {McpServiceTokenDocument} from "../types/mcpServiceToken";
11
+
12
+ export const MAX_ACTIVE_MCP_SERVICE_TOKENS = 10;
13
+
14
+ const DEFAULT_LIST_LIMIT = 100;
15
+ const MAX_LIST_LIMIT = 100;
16
+
17
+ export interface McpServiceTokenRoutesOptions {
18
+ openApi?: OpenApiMiddleware;
19
+ publicMcpUrl?: string;
20
+ }
21
+
22
+ export type McpServiceTokensAppOption =
23
+ | boolean
24
+ | {
25
+ enabled: boolean;
26
+ publicMcpUrl?: string;
27
+ };
28
+
29
+ export const resolveMcpServiceTokensOption = (
30
+ option: McpServiceTokensAppOption | undefined
31
+ ): {enabled: boolean; publicMcpUrl?: string} => {
32
+ if (option === true) {
33
+ return {enabled: true};
34
+ }
35
+ if (option && typeof option === "object" && option.enabled === true) {
36
+ return {enabled: true, publicMcpUrl: option.publicMcpUrl};
37
+ }
38
+ return {enabled: false};
39
+ };
40
+
41
+ const bearerFromRequest = (req: Request): string | undefined => {
42
+ const authorization = req.headers.authorization;
43
+ if (typeof authorization !== "string") {
44
+ return undefined;
45
+ }
46
+ if (authorization.startsWith("Bearer ")) {
47
+ return authorization.slice("Bearer ".length);
48
+ }
49
+ return authorization;
50
+ };
51
+
52
+ const rejectMcpServiceTokenBearer = (req: Request, _res: Response, next: NextFunction): void => {
53
+ const token = bearerFromRequest(req);
54
+ if (token?.startsWith("mcp_")) {
55
+ next(new UnauthorizedError("MCP service tokens cannot manage service tokens"));
56
+ return;
57
+ }
58
+ next();
59
+ };
60
+
61
+ const requireAuthenticatedUser = (req: Request): User => {
62
+ const user = req.user as unknown as User | undefined;
63
+ if (!user?._id) {
64
+ throw new UnauthorizedError("Unauthorized");
65
+ }
66
+ return user;
67
+ };
68
+
69
+ const parseName = (value: unknown): string => {
70
+ if (typeof value !== "string") {
71
+ throw new BadRequestError({title: "name is required"});
72
+ }
73
+ const name = value.trim();
74
+ if (!name) {
75
+ throw new BadRequestError({title: "name is required"});
76
+ }
77
+ return name;
78
+ };
79
+
80
+ const parseExpiresAt = (value: unknown): Date | undefined => {
81
+ if (value === undefined || value === null || value === "") {
82
+ return undefined;
83
+ }
84
+ if (typeof value !== "string") {
85
+ throw new BadRequestError({title: "expiresAt must be an ISO-8601 datetime string"});
86
+ }
87
+ const parsed = DateTime.fromISO(value, {setZone: true});
88
+ if (!parsed.isValid) {
89
+ throw new BadRequestError({title: "expiresAt must be an ISO-8601 datetime string"});
90
+ }
91
+ if (parsed.toMillis() <= DateTime.now().toMillis()) {
92
+ throw new BadRequestError({title: "expiresAt must be in the future"});
93
+ }
94
+ return parsed.toUTC().toJSDate();
95
+ };
96
+
97
+ const parsePage = (value: unknown): number => {
98
+ if (value === undefined) {
99
+ return 1;
100
+ }
101
+ const page = Number(value);
102
+ if (!Number.isInteger(page) || page < 1) {
103
+ throw new BadRequestError({code: "invalid-page", title: "Invalid page"});
104
+ }
105
+ return page;
106
+ };
107
+
108
+ const parseLimit = (value: unknown): number => {
109
+ if (value === undefined) {
110
+ return DEFAULT_LIST_LIMIT;
111
+ }
112
+ const limit = Number(value);
113
+ if (!Number.isInteger(limit) || limit < 1) {
114
+ throw new BadRequestError({title: "Invalid limit"});
115
+ }
116
+ return Math.min(limit, MAX_LIST_LIMIT);
117
+ };
118
+
119
+ const resolveMcpUrl = (req: Request, publicMcpUrl?: string): string => {
120
+ const configured = publicMcpUrl ?? process.env.BETTER_AUTH_URL;
121
+ if (configured) {
122
+ const base = configured.replace(/\/$/, "");
123
+ if (base.endsWith("/mcp")) {
124
+ return base;
125
+ }
126
+ return `${base}/mcp`;
127
+ }
128
+ const host = req.get("host") ?? "localhost";
129
+ return `${req.protocol}://${host}/mcp`;
130
+ };
131
+
132
+ const toListItem = (doc: McpServiceTokenDocument): Record<string, unknown> => {
133
+ return {
134
+ created: doc.created.toISOString(),
135
+ expiresAt: doc.expiresAt ? doc.expiresAt.toISOString() : null,
136
+ id: String(doc._id),
137
+ lastUsedAt: doc.lastUsedAt ? doc.lastUsedAt.toISOString() : null,
138
+ name: doc.name,
139
+ revokedAt: doc.revokedAt ? doc.revokedAt.toISOString() : null,
140
+ tokenPrefix: doc.tokenPrefix,
141
+ };
142
+ };
143
+
144
+ const serviceTokenGuards = [rejectMcpServiceTokenBearer, authenticateMiddleware()];
145
+
146
+ const createdTokenFields = {
147
+ created: {type: "string"},
148
+ expiresAt: {type: "string"},
149
+ id: {type: "string"},
150
+ mcpUrl: {type: "string"},
151
+ name: {type: "string"},
152
+ token: {type: "string"},
153
+ tokenPrefix: {type: "string"},
154
+ };
155
+
156
+ export const addMcpServiceTokenRoutes = (
157
+ app: Application,
158
+ options: McpServiceTokenRoutesOptions = {}
159
+ ): void => {
160
+ const openApiOptions = {openApi: options.openApi};
161
+
162
+ app.post(
163
+ "/mcp/service-tokens",
164
+ [
165
+ ...serviceTokenGuards,
166
+ createOpenApiBuilder(openApiOptions)
167
+ .withTags(["mcp"])
168
+ .withOperationId("createMcpServiceToken")
169
+ .withSummary("Create an MCP service token")
170
+ .withDescription(
171
+ "Mints a personal MCP service token that acts as the signed-in user on POST /mcp. The plaintext token is returned once."
172
+ )
173
+ .withRequestBody({
174
+ expiresAt: {
175
+ description: "Optional ISO-8601 expiry; omit for a token that does not expire",
176
+ type: "string",
177
+ },
178
+ name: {
179
+ description: "User-visible label for this token",
180
+ required: true,
181
+ type: "string",
182
+ },
183
+ })
184
+ .withResponse(200, {
185
+ data: {
186
+ properties: createdTokenFields,
187
+ type: "object",
188
+ },
189
+ })
190
+ .build(),
191
+ ],
192
+ asyncHandler(async (req, res) => {
193
+ const user = requireAuthenticatedUser(req);
194
+ const name = parseName(req.body?.name);
195
+ const expiresAt = parseExpiresAt(req.body?.expiresAt);
196
+ const activeCount = await McpServiceToken.countActiveForUser(
197
+ new mongoose.Types.ObjectId(String(user._id))
198
+ );
199
+ if (activeCount >= MAX_ACTIVE_MCP_SERVICE_TOKENS) {
200
+ throw new BadRequestError({
201
+ title: `Maximum of ${MAX_ACTIVE_MCP_SERVICE_TOKENS} active MCP service tokens`,
202
+ });
203
+ }
204
+ const issued = await McpServiceToken.issueFor({_id: user._id}, {expiresAt, name});
205
+ return res.json({
206
+ data: {
207
+ created: issued.mcpServiceToken.created.toISOString(),
208
+ expiresAt: issued.mcpServiceToken.expiresAt
209
+ ? issued.mcpServiceToken.expiresAt.toISOString()
210
+ : null,
211
+ id: String(issued.mcpServiceToken._id),
212
+ mcpUrl: resolveMcpUrl(req, options.publicMcpUrl),
213
+ name: issued.mcpServiceToken.name,
214
+ token: issued.token,
215
+ tokenPrefix: issued.mcpServiceToken.tokenPrefix,
216
+ },
217
+ });
218
+ })
219
+ );
220
+
221
+ app.get(
222
+ "/mcp/service-tokens",
223
+ [
224
+ ...serviceTokenGuards,
225
+ createOpenApiBuilder(openApiOptions)
226
+ .withTags(["mcp"])
227
+ .withOperationId("listMcpServiceTokens")
228
+ .withSummary("List MCP service tokens")
229
+ .withDescription(
230
+ "Lists MCP service tokens owned by the signed-in user. Never includes plaintext or tokenHash."
231
+ )
232
+ .withQueryParameter("page", {type: "number"}, {required: false})
233
+ .withQueryParameter("limit", {type: "number"}, {required: false})
234
+ .withResponse(200, {
235
+ data: {type: "array"},
236
+ limit: {type: "number"},
237
+ more: {type: "boolean"},
238
+ page: {type: "number"},
239
+ total: {type: "number"},
240
+ })
241
+ .build(),
242
+ ],
243
+ asyncHandler(async (req, res) => {
244
+ const user = requireAuthenticatedUser(req);
245
+ const page = parsePage(req.query.page);
246
+ const limit = parseLimit(req.query.limit);
247
+ const filter = {userId: new mongoose.Types.ObjectId(String(user._id))};
248
+ const total = await McpServiceToken.countDocuments(filter);
249
+ const docs = await McpServiceToken.find(filter)
250
+ .sort("-created")
251
+ .skip((page - 1) * limit)
252
+ .limit(limit + 1);
253
+ const more = docs.length > limit;
254
+ const pageDocs = more ? docs.slice(0, limit) : docs;
255
+ return res.json({
256
+ data: pageDocs.map(toListItem),
257
+ limit,
258
+ more,
259
+ page,
260
+ total,
261
+ });
262
+ })
263
+ );
264
+
265
+ app.delete(
266
+ "/mcp/service-tokens/:id",
267
+ [
268
+ ...serviceTokenGuards,
269
+ createOpenApiBuilder(openApiOptions)
270
+ .withTags(["mcp"])
271
+ .withOperationId("revokeMcpServiceToken")
272
+ .withSummary("Revoke an MCP service token")
273
+ .withDescription("Sets revokedAt on a token owned by the signed-in user.")
274
+ .withPathParameter("id", {type: "string"})
275
+ .withResponse(200, {
276
+ data: {
277
+ properties: {
278
+ id: {type: "string"},
279
+ revokedAt: {type: "string"},
280
+ },
281
+ type: "object",
282
+ },
283
+ })
284
+ .build(),
285
+ ],
286
+ asyncHandler(async (req, res) => {
287
+ const user = requireAuthenticatedUser(req);
288
+ const tokenId = req.params.id;
289
+ if (!mongoose.Types.ObjectId.isValid(tokenId)) {
290
+ throw new NotFoundError("MCP service token not found");
291
+ }
292
+ const revoked = await McpServiceToken.revokeForUser(
293
+ {_id: user._id},
294
+ new mongoose.Types.ObjectId(tokenId)
295
+ );
296
+ if (!revoked) {
297
+ throw new NotFoundError("MCP service token not found");
298
+ }
299
+ return res.json({
300
+ data: {
301
+ id: String(revoked._id),
302
+ revokedAt: revoked.revokedAt ? revoked.revokedAt.toISOString() : null,
303
+ },
304
+ });
305
+ })
306
+ );
307
+ };
@@ -236,7 +236,7 @@ describe("tool-call observability", () => {
236
236
  const logs = await captureLogs(async () => {
237
237
  const result = await tool.handler({});
238
238
  expect(result.isError).toBe(true);
239
- expect(result.content[0].text).toContain("Create failed");
239
+ expect(result.content[0].text).toContain("Validation failed");
240
240
  expect(result.content[0].text).not.toContain("ValidationError:");
241
241
  expect(Object.keys(result)).toEqual(["content", "isError"]);
242
242
  });
package/src/mcp/types.ts CHANGED
@@ -85,11 +85,7 @@ export interface MCPConfig {
85
85
 
86
86
  export interface MCPRegistryEntry {
87
87
  modelName: string;
88
- // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
89
- // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
90
- model: Model<any>;
88
+ model: Model<unknown>;
91
89
  config: MCPConfig;
92
- // noExplicitAny: ModelRouterOptions is generic over the consumer's document type
93
- // biome-ignore lint/suspicious/noExplicitAny: ModelRouterOptions is generic over the consumer's document type
94
- options: ModelRouterOptions<any>;
90
+ options: ModelRouterOptions<unknown>;
95
91
  }
@@ -0,0 +1,129 @@
1
+ import {beforeEach, describe, it} from "bun:test";
2
+ import {createHash} from "node:crypto";
3
+ import {assert} from "chai";
4
+ import {DateTime} from "luxon";
5
+ import mongoose from "mongoose";
6
+
7
+ import {McpServiceToken} from "./mcpServiceToken";
8
+
9
+ const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
10
+
11
+ describe("McpServiceToken", () => {
12
+ beforeEach(async () => {
13
+ await McpServiceToken.deleteMany({});
14
+ await McpServiceToken.syncIndexes();
15
+ });
16
+
17
+ it("issues an mcp_ token and stores only its SHA-256 hash", async () => {
18
+ const userId = new mongoose.Types.ObjectId();
19
+ const issued = await McpServiceToken.issueFor({_id: userId}, {name: "Perplexity"});
20
+
21
+ assert.match(issued.token, /^mcp_[0-9a-f]{64}$/);
22
+ assert.equal(issued.mcpServiceToken.name, "Perplexity");
23
+ assert.equal(issued.mcpServiceToken.tokenHash, hashToken(issued.token));
24
+ assert.equal(issued.mcpServiceToken.tokenPrefix, issued.token.slice(4, 12));
25
+ assert.notInclude(JSON.stringify(issued.mcpServiceToken.toJSON()), issued.token);
26
+ });
27
+
28
+ it("verifies an active token but not a revoked or expired token", async () => {
29
+ const userId = new mongoose.Types.ObjectId();
30
+ const active = await McpServiceToken.issueFor({_id: userId}, {name: "Active"});
31
+ const revoked = await McpServiceToken.issueFor({_id: userId}, {name: "Revoked"});
32
+ const expired = await McpServiceToken.issueFor(
33
+ {_id: userId},
34
+ {expiresAt: DateTime.now().minus({minute: 1}).toJSDate(), name: "Expired"}
35
+ );
36
+
37
+ const revokedToken = await McpServiceToken.revokeForUser(
38
+ {_id: userId},
39
+ revoked.mcpServiceToken._id
40
+ );
41
+
42
+ assert.equal(
43
+ (await McpServiceToken.verify(active.token))?._id.toString(),
44
+ active.mcpServiceToken._id.toString()
45
+ );
46
+ assert.isDefined(revokedToken?.revokedAt);
47
+ assert.isNull(await McpServiceToken.verify(revoked.token));
48
+ assert.isNull(await McpServiceToken.verify(expired.token));
49
+ assert.isNull(await McpServiceToken.verify("mcp_unknown"));
50
+ });
51
+
52
+ it("allows only the owner to revoke an active token once", async () => {
53
+ const ownerId = new mongoose.Types.ObjectId();
54
+ const otherUserId = new mongoose.Types.ObjectId();
55
+ const issued = await McpServiceToken.issueFor({_id: ownerId}, {name: "Owner token"});
56
+
57
+ assert.isNull(
58
+ await McpServiceToken.revokeForUser({_id: otherUserId}, issued.mcpServiceToken._id)
59
+ );
60
+
61
+ const revoked = await McpServiceToken.revokeForUser({_id: ownerId}, issued.mcpServiceToken._id);
62
+ assert.equal(revoked?._id.toString(), issued.mcpServiceToken._id.toString());
63
+ assert.instanceOf(revoked?.revokedAt, Date);
64
+
65
+ assert.isNull(await McpServiceToken.revokeForUser({_id: ownerId}, issued.mcpServiceToken._id));
66
+ assert.isNull(
67
+ await McpServiceToken.revokeForUser({_id: ownerId}, new mongoose.Types.ObjectId())
68
+ );
69
+ });
70
+
71
+ it("enforces unique token hashes", async () => {
72
+ const tokenHash = "same-hash";
73
+ const tokenFields = {
74
+ name: "Duplicate",
75
+ tokenHash,
76
+ tokenPrefix: "duplicate",
77
+ userId: new mongoose.Types.ObjectId(),
78
+ };
79
+
80
+ await McpServiceToken.create(tokenFields);
81
+
82
+ let error: unknown;
83
+ try {
84
+ await McpServiceToken.create(tokenFields);
85
+ } catch (caughtError) {
86
+ error = caughtError;
87
+ }
88
+
89
+ assert.instanceOf(error, Error);
90
+ assert.match(error.message, /duplicate key/i);
91
+ });
92
+
93
+ it("counts only active tokens for a user", async () => {
94
+ const userId = new mongoose.Types.ObjectId();
95
+ const otherUserId = new mongoose.Types.ObjectId();
96
+ const revoked = await McpServiceToken.issueFor({_id: userId}, {name: "Revoked"});
97
+ await McpServiceToken.issueFor({_id: userId}, {name: "Active"});
98
+ await McpServiceToken.issueFor(
99
+ {_id: userId},
100
+ {expiresAt: DateTime.now().minus({minute: 1}).toJSDate(), name: "Expired"}
101
+ );
102
+ await McpServiceToken.issueFor({_id: otherUserId}, {name: "Other"});
103
+ await McpServiceToken.revokeForUser({_id: userId}, revoked.mcpServiceToken._id);
104
+
105
+ assert.equal(await McpServiceToken.countActiveForUser(userId), 1);
106
+ });
107
+
108
+ it("revokes on document deleteOne instead of removing the row", async () => {
109
+ const userId = new mongoose.Types.ObjectId();
110
+ const issued = await McpServiceToken.issueFor({_id: userId}, {name: "Admin delete"});
111
+
112
+ await issued.mcpServiceToken.deleteOne();
113
+
114
+ const stored = await McpServiceToken.findById(issued.mcpServiceToken._id);
115
+ assert.isDefined(stored?.revokedAt);
116
+ assert.isNull(await McpServiceToken.verify(issued.token));
117
+ });
118
+
119
+ it("revokes on query deleteOne used by admin DELETE", async () => {
120
+ const userId = new mongoose.Types.ObjectId();
121
+ const issued = await McpServiceToken.issueFor({_id: userId}, {name: "Query delete"});
122
+
123
+ await McpServiceToken.deleteOne({_id: issued.mcpServiceToken._id});
124
+
125
+ const stored = await McpServiceToken.findById(issued.mcpServiceToken._id);
126
+ assert.isDefined(stored?.revokedAt);
127
+ assert.isNull(await McpServiceToken.verify(issued.token));
128
+ });
129
+ });
@@ -0,0 +1,158 @@
1
+ import {createHash, randomBytes} from "node:crypto";
2
+ import {DateTime} from "luxon";
3
+ import mongoose from "mongoose";
4
+
5
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone, findOneOrNoneFor} from "../plugins";
6
+ import type {McpServiceTokenDocument, McpServiceTokenModel} from "../types/mcpServiceToken";
7
+
8
+ export type {
9
+ McpServiceTokenDocument,
10
+ McpServiceTokenIssueOptions,
11
+ McpServiceTokenModel,
12
+ McpServiceTokenStatics,
13
+ } from "../types/mcpServiceToken";
14
+
15
+ const MCP_SERVICE_TOKEN_PREFIX = "mcp_";
16
+ const MCP_SERVICE_TOKEN_RANDOM_BYTES = 32;
17
+ const MCP_SERVICE_TOKEN_DISPLAY_LENGTH = 8;
18
+
19
+ const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
20
+
21
+ const mcpServiceTokenSchema = new mongoose.Schema<McpServiceTokenDocument, McpServiceTokenModel>(
22
+ {
23
+ expiresAt: {
24
+ description: "When this MCP service token expires; unset when it does not expire",
25
+ type: Date,
26
+ },
27
+ lastUsedAt: {
28
+ description: "When this MCP service token most recently authenticated an MCP request",
29
+ type: Date,
30
+ },
31
+ name: {
32
+ description: "User-provided label identifying the MCP service token",
33
+ required: true,
34
+ trim: true,
35
+ type: String,
36
+ },
37
+ revokedAt: {
38
+ description: "When this MCP service token was revoked; unset while it remains active",
39
+ type: Date,
40
+ },
41
+ tokenHash: {
42
+ description: "SHA-256 hash of the full MCP service token plaintext",
43
+ required: true,
44
+ type: String,
45
+ unique: true,
46
+ },
47
+ tokenPrefix: {
48
+ description: "First eight characters after mcp_ used to identify the token safely",
49
+ required: true,
50
+ type: String,
51
+ },
52
+ userId: {
53
+ description: "The user this MCP service token acts as",
54
+ index: true,
55
+ ref: "User",
56
+ required: true,
57
+ type: mongoose.Schema.Types.ObjectId,
58
+ },
59
+ },
60
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
61
+ );
62
+
63
+ mcpServiceTokenSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
64
+ mcpServiceTokenSchema.index({revokedAt: 1, userId: 1});
65
+
66
+ mcpServiceTokenSchema.plugin(createdUpdatedPlugin);
67
+ mcpServiceTokenSchema.plugin(findOneOrNone);
68
+ mcpServiceTokenSchema.plugin(findExactlyOne);
69
+
70
+ const revokeInsteadOfDelete = async (
71
+ doc: McpServiceTokenDocument | null
72
+ ): Promise<McpServiceTokenDocument | null> => {
73
+ if (!doc) {
74
+ return null;
75
+ }
76
+ if (!doc.revokedAt) {
77
+ doc.set("revokedAt", DateTime.now().toJSDate());
78
+ await doc.save();
79
+ }
80
+ return doc;
81
+ };
82
+
83
+ mcpServiceTokenSchema.methods = {
84
+ ...mcpServiceTokenSchema.methods,
85
+ async deleteOne(this: McpServiceTokenDocument): Promise<McpServiceTokenDocument> {
86
+ const revoked = await revokeInsteadOfDelete(this);
87
+ return revoked ?? this;
88
+ },
89
+ };
90
+
91
+ mcpServiceTokenSchema.pre("deleteOne", {document: false, query: true}, async function () {
92
+ const existing = await findOneOrNoneFor(this.model, this.getFilter());
93
+ await revokeInsteadOfDelete(existing as McpServiceTokenDocument | null);
94
+ this.setQuery({_id: {$exists: false}});
95
+ });
96
+
97
+ mcpServiceTokenSchema.statics = {
98
+ ...mcpServiceTokenSchema.statics,
99
+ async countActiveForUser(
100
+ this: McpServiceTokenModel,
101
+ userId: mongoose.Types.ObjectId
102
+ ): Promise<number> {
103
+ const now = DateTime.now().toJSDate();
104
+ return this.countDocuments({
105
+ $or: [{expiresAt: {$exists: false}}, {expiresAt: {$gt: now}}],
106
+ revokedAt: {$exists: false},
107
+ userId,
108
+ });
109
+ },
110
+ async issueFor(
111
+ this: McpServiceTokenModel,
112
+ user: {_id: {toString(): string}},
113
+ options: {expiresAt?: Date; name: string}
114
+ ): Promise<{mcpServiceToken: McpServiceTokenDocument; token: string}> {
115
+ const token = `${MCP_SERVICE_TOKEN_PREFIX}${randomBytes(MCP_SERVICE_TOKEN_RANDOM_BYTES).toString("hex")}`;
116
+ const mcpServiceToken = await this.create({
117
+ expiresAt: options.expiresAt,
118
+ name: options.name,
119
+ tokenHash: hashToken(token),
120
+ tokenPrefix: token.slice(
121
+ MCP_SERVICE_TOKEN_PREFIX.length,
122
+ MCP_SERVICE_TOKEN_PREFIX.length + MCP_SERVICE_TOKEN_DISPLAY_LENGTH
123
+ ),
124
+ userId: new mongoose.Types.ObjectId(String(user._id)),
125
+ });
126
+ return {mcpServiceToken, token};
127
+ },
128
+ async revokeForUser(
129
+ this: McpServiceTokenModel,
130
+ user: {_id: {toString(): string}},
131
+ tokenId: mongoose.Types.ObjectId
132
+ ): Promise<McpServiceTokenDocument | null> {
133
+ return this.findOneAndUpdate(
134
+ {
135
+ _id: tokenId,
136
+ revokedAt: {$exists: false},
137
+ userId: new mongoose.Types.ObjectId(String(user._id)),
138
+ },
139
+ {$set: {revokedAt: DateTime.now().toJSDate()}},
140
+ {returnDocument: "after"}
141
+ );
142
+ },
143
+ async verify(this: McpServiceTokenModel, token: string): Promise<McpServiceTokenDocument | null> {
144
+ const now = DateTime.now().toJSDate();
145
+ return this.findOneOrNone({
146
+ $or: [{expiresAt: {$exists: false}}, {expiresAt: {$gt: now}}],
147
+ revokedAt: {$exists: false},
148
+ tokenHash: hashToken(token),
149
+ });
150
+ },
151
+ };
152
+
153
+ export const McpServiceToken =
154
+ (mongoose.models.McpServiceToken as McpServiceTokenModel | undefined) ??
155
+ mongoose.model<McpServiceTokenDocument, McpServiceTokenModel>(
156
+ "McpServiceToken",
157
+ mcpServiceTokenSchema
158
+ );