@terreno/api 57.20.0 → 58.0.0-beta.1

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 (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
@@ -1,19 +1,34 @@
1
1
  import type {Application, NextFunction, Request, Response} from "express";
2
2
  import {DateTime} from "luxon";
3
- import mongoose from "mongoose";
3
+ import type {Document} from "mongoose";
4
4
 
5
- import {asyncHandler, type OpenApiMiddleware} from "../api";
6
- import {authenticateMiddleware, type User} from "../auth";
5
+ import {
6
+ type ModelRouterOptions,
7
+ type ModelRouterRegistration,
8
+ modelRouter,
9
+ type OpenApiMiddleware,
10
+ type RESTMethod,
11
+ } from "../api";
12
+ import type {User} from "../auth";
7
13
  import {BadRequestError, NotFoundError, UnauthorizedError} from "../errors";
8
14
  import {MCP_SERVICE_TOKEN_PREFIX, McpServiceToken} from "../models/mcpServiceToken";
9
- import {createOpenApiBuilder} from "../openApiBuilder";
15
+ import {Permissions} from "../permissions";
16
+ import {defaultResponseHandler} from "../transformers";
10
17
  import type {McpServiceTokenDocument} from "../types/mcpServiceToken";
18
+ import {z} from "../zodOpenApi";
11
19
  import {userTokenEpoch} from "./auth";
12
20
 
13
21
  export const MAX_ACTIVE_MCP_SERVICE_TOKENS = 10;
14
22
 
23
+ /** Route path of the self-serve MCP service token router. */
24
+ export const MCP_SERVICE_TOKENS_ROUTE_PATH = "/mcp/service-tokens";
25
+
26
+ /** Sync collection tag clients subscribe to (`mcp/service-tokens|owner:{userId}`). */
27
+ export const MCP_SERVICE_TOKENS_SYNC_COLLECTION = "mcp/service-tokens";
28
+
15
29
  const DEFAULT_LIST_LIMIT = 100;
16
30
  const MAX_LIST_LIMIT = 100;
31
+ const ACTION_TAG = "mcpServiceTokens";
17
32
 
18
33
  export interface McpServiceTokenRoutesOptions {
19
34
  openApi?: OpenApiMiddleware;
@@ -59,18 +74,14 @@ const rejectMcpServiceTokenBearer = (req: Request, _res: Response, next: NextFun
59
74
  next();
60
75
  };
61
76
 
62
- const requireAuthenticatedUser = (req: Request): User => {
63
- const user = req.user as unknown as User | undefined;
77
+ const requireAuthenticatedUser = (user: User | undefined): User => {
64
78
  if (!user?._id) {
65
79
  throw new UnauthorizedError("Unauthorized");
66
80
  }
67
81
  return user;
68
82
  };
69
83
 
70
- const parseName = (value: unknown): string => {
71
- if (typeof value !== "string") {
72
- throw new BadRequestError({title: "name is required"});
73
- }
84
+ const parseName = (value: string): string => {
74
85
  const name = value.trim();
75
86
  if (!name) {
76
87
  throw new BadRequestError({title: "name is required"});
@@ -78,13 +89,10 @@ const parseName = (value: unknown): string => {
78
89
  return name;
79
90
  };
80
91
 
81
- const parseExpiresAt = (value: unknown): Date | undefined => {
92
+ const parseExpiresAt = (value: string | null | undefined): Date | undefined => {
82
93
  if (value === undefined || value === null || value === "") {
83
94
  return undefined;
84
95
  }
85
- if (typeof value !== "string") {
86
- throw new BadRequestError({title: "expiresAt must be an ISO-8601 datetime string"});
87
- }
88
96
  const parsed = DateTime.fromISO(value, {setZone: true});
89
97
  if (!parsed.isValid) {
90
98
  throw new BadRequestError({title: "expiresAt must be an ISO-8601 datetime string"});
@@ -95,28 +103,6 @@ const parseExpiresAt = (value: unknown): Date | undefined => {
95
103
  return parsed.toUTC().toJSDate();
96
104
  };
97
105
 
98
- const parsePage = (value: unknown): number => {
99
- if (value === undefined) {
100
- return 1;
101
- }
102
- const page = Number(value);
103
- if (!Number.isInteger(page) || page < 1) {
104
- throw new BadRequestError({code: "invalid-page", title: "Invalid page"});
105
- }
106
- return page;
107
- };
108
-
109
- const parseLimit = (value: unknown): number => {
110
- if (value === undefined) {
111
- return DEFAULT_LIST_LIMIT;
112
- }
113
- const limit = Number(value);
114
- if (!Number.isInteger(limit) || limit < 1) {
115
- throw new BadRequestError({title: "Invalid limit"});
116
- }
117
- return Math.min(limit, MAX_LIST_LIMIT);
118
- };
119
-
120
106
  const resolveMcpUrl = (req: Request, publicMcpUrl?: string): string => {
121
107
  const configured = publicMcpUrl ?? process.env.BETTER_AUTH_URL;
122
108
  if (configured) {
@@ -130,191 +116,186 @@ const resolveMcpUrl = (req: Request, publicMcpUrl?: string): string => {
130
116
  return `${req.protocol}://${host}/mcp`;
131
117
  };
132
118
 
133
- const toListItem = (doc: McpServiceTokenDocument): Record<string, unknown> => {
134
- return {
135
- created: doc.created.toISOString(),
136
- expiresAt: doc.expiresAt ? doc.expiresAt.toISOString() : null,
137
- id: String(doc._id),
138
- lastUsedAt: doc.lastUsedAt ? doc.lastUsedAt.toISOString() : null,
139
- name: doc.name,
140
- revokedAt: doc.revokedAt ? doc.revokedAt.toISOString() : null,
141
- tokenPrefix: doc.tokenPrefix,
142
- };
119
+ /**
120
+ * Public shape of a stored MCP service token: every field except `tokenHash`, plus `id`.
121
+ * Used for REST responses, sync snapshots, and sync deltas so the hash never leaves the server.
122
+ */
123
+ export const toPublicMcpServiceToken = (doc: Record<string, unknown>): Record<string, unknown> => {
124
+ const {tokenHash: _tokenHash, ...rest} = doc;
125
+ return {...rest, id: String(doc._id)};
143
126
  };
144
127
 
145
- const serviceTokenGuards = [rejectMcpServiceTokenBearer, authenticateMiddleware()];
128
+ const stripTokenHash = (value: unknown): unknown => {
129
+ if (Array.isArray(value)) {
130
+ return value.map(stripTokenHash);
131
+ }
132
+ if (value && typeof value === "object") {
133
+ const {tokenHash: _tokenHash, ...rest} = value as Record<string, unknown>;
134
+ return rest;
135
+ }
136
+ return value;
137
+ };
146
138
 
147
- const createdTokenFields = {
148
- created: {type: "string"},
149
- expiresAt: {type: "string"},
150
- id: {type: "string"},
151
- mcpUrl: {type: "string"},
152
- name: {type: "string"},
153
- token: {type: "string"},
154
- tokenPrefix: {type: "string"},
139
+ const mcpServiceTokenResponseHandler = async (
140
+ value: Document | Document[],
141
+ method: "list" | "create" | "read" | "update" | "delete",
142
+ req: Request,
143
+ options: ModelRouterOptions<McpServiceTokenDocument>
144
+ ): Promise<never> => {
145
+ const serialized = await defaultResponseHandler(
146
+ value as never,
147
+ method as "list" | "create" | "read" | "update",
148
+ req,
149
+ options
150
+ );
151
+ return stripTokenHash(serialized) as never;
155
152
  };
156
153
 
157
- export const addMcpServiceTokenRoutes = (
158
- app: Application,
159
- options: McpServiceTokenRoutesOptions = {}
160
- ): void => {
161
- const openApiOptions = {openApi: options.openApi};
154
+ /** Read access is owner-only (no admin bypass: admins use the admin panel). */
155
+ const isTokenOwner = (_method: RESTMethod, user?: User, obj?: unknown): boolean => {
156
+ if (!user?.id) {
157
+ return false;
158
+ }
159
+ if (!obj) {
160
+ return true;
161
+ }
162
+ return String((obj as {userId?: unknown}).userId) === String(user.id);
163
+ };
162
164
 
163
- app.post(
164
- "/mcp/service-tokens",
165
- [
166
- ...serviceTokenGuards,
167
- createOpenApiBuilder(openApiOptions)
168
- .withTags(["mcp"])
169
- .withOperationId("createMcpServiceToken")
170
- .withSummary("Create an MCP service token")
171
- .withDescription(
172
- "Mints a personal MCP service token that acts as the signed-in user on POST /mcp. The plaintext token is returned once."
173
- )
174
- .withRequestBody({
175
- expiresAt: {
176
- description: "Optional ISO-8601 expiry; omit for a token that does not expire",
177
- type: "string",
178
- },
179
- name: {
180
- description: "User-visible label for this token",
181
- required: true,
182
- type: "string",
183
- },
184
- })
185
- .withResponse(200, {
186
- data: {
187
- properties: createdTokenFields,
188
- type: "object",
189
- },
190
- })
191
- .build(),
192
- ],
193
- asyncHandler(async (req, res) => {
194
- const user = requireAuthenticatedUser(req);
195
- const name = parseName(req.body?.name);
196
- const expiresAt = parseExpiresAt(req.body?.expiresAt);
197
- await McpServiceToken.revokeOutdatedForUser({
198
- _id: user._id,
199
- tokenEpoch: userTokenEpoch(user),
200
- });
201
- const activeCount = await McpServiceToken.countActiveForUser(
202
- new mongoose.Types.ObjectId(String(user._id))
203
- );
204
- if (activeCount >= MAX_ACTIVE_MCP_SERVICE_TOKENS) {
205
- throw new BadRequestError({
206
- title: `Maximum of ${MAX_ACTIVE_MCP_SERVICE_TOKENS} active MCP service tokens`,
207
- });
208
- }
209
- const issued = await McpServiceToken.issueFor(
210
- {_id: user._id, tokenEpoch: userTokenEpoch(user)},
211
- {expiresAt, name}
212
- );
213
- return res.json({
214
- data: {
215
- created: issued.mcpServiceToken.created.toISOString(),
216
- expiresAt: issued.mcpServiceToken.expiresAt
217
- ? issued.mcpServiceToken.expiresAt.toISOString()
218
- : null,
219
- id: String(issued.mcpServiceToken._id),
220
- mcpUrl: resolveMcpUrl(req, options.publicMcpUrl),
221
- name: issued.mcpServiceToken.name,
222
- token: issued.token,
223
- tokenPrefix: issued.mcpServiceToken.tokenPrefix,
224
- },
225
- });
226
- })
227
- );
165
+ const createBody = z.object({
166
+ expiresAt: z
167
+ .string()
168
+ .nullable()
169
+ .optional()
170
+ .describe("Optional ISO-8601 expiry; omit for a token that does not expire"),
171
+ name: z.string().describe("User-visible label for this token"),
172
+ });
173
+
174
+ const createdTokenResponse = z.object({
175
+ created: z.string(),
176
+ expiresAt: z.string().nullable(),
177
+ id: z.string(),
178
+ mcpUrl: z.string(),
179
+ name: z.string(),
180
+ token: z.string().describe("The plaintext mcp_ token. Returned only by this response."),
181
+ tokenPrefix: z.string(),
182
+ });
228
183
 
229
- app.get(
230
- "/mcp/service-tokens",
231
- [
232
- ...serviceTokenGuards,
233
- createOpenApiBuilder(openApiOptions)
234
- .withTags(["mcp"])
235
- .withOperationId("listMcpServiceTokens")
236
- .withSummary("List MCP service tokens")
237
- .withDescription(
238
- "Lists MCP service tokens owned by the signed-in user. Never includes plaintext or tokenHash."
239
- )
240
- .withQueryParameter("page", {type: "number"}, {required: false})
241
- .withQueryParameter("limit", {type: "number"}, {required: false})
242
- .withResponse(200, {
243
- data: {type: "array"},
244
- limit: {type: "number"},
245
- more: {type: "boolean"},
246
- page: {type: "number"},
247
- total: {type: "number"},
248
- })
249
- .build(),
250
- ],
251
- asyncHandler(async (req, res) => {
252
- const user = requireAuthenticatedUser(req);
253
- const page = parsePage(req.query.page);
254
- const limit = parseLimit(req.query.limit);
255
- // Tokens from before a password reset or session revocation no longer work; list them so.
184
+ /**
185
+ * Build the self-serve `/mcp/service-tokens` router. The collection is synced read-only
186
+ * (owner scope on `userId`): list/read over REST and sync, no client create/update/delete.
187
+ * Minting and revoking are the `create` collection action and `revoke` instance action.
188
+ */
189
+ export const createMcpServiceTokenRouter = (
190
+ options: McpServiceTokenRoutesOptions = {}
191
+ ): ModelRouterRegistration =>
192
+ modelRouter<McpServiceTokenDocument>(MCP_SERVICE_TOKENS_ROUTE_PATH, McpServiceToken, {
193
+ collectionActions: {
194
+ create: {
195
+ body: createBody,
196
+ description:
197
+ "Mints a personal MCP service token that acts as the signed-in user on POST /mcp. The plaintext token is returned once.",
198
+ handler: async ({body, req, user}) => {
199
+ const owner = requireAuthenticatedUser(user);
200
+ const {expiresAt: rawExpiresAt, name: rawName} = body as z.infer<typeof createBody>;
201
+ const name = parseName(rawName);
202
+ const expiresAt = parseExpiresAt(rawExpiresAt);
203
+ await McpServiceToken.revokeOutdatedForUser({
204
+ _id: owner._id,
205
+ tokenEpoch: userTokenEpoch(owner),
206
+ });
207
+ const activeCount = await McpServiceToken.countActiveForUser(String(owner._id));
208
+ if (activeCount >= MAX_ACTIVE_MCP_SERVICE_TOKENS) {
209
+ throw new BadRequestError({
210
+ title: `Maximum of ${MAX_ACTIVE_MCP_SERVICE_TOKENS} active MCP service tokens`,
211
+ });
212
+ }
213
+ const issued = await McpServiceToken.issueFor(
214
+ {_id: owner._id, tokenEpoch: userTokenEpoch(owner)},
215
+ {expiresAt, name}
216
+ );
217
+ return {
218
+ created: issued.mcpServiceToken.created.toISOString(),
219
+ expiresAt: issued.mcpServiceToken.expiresAt
220
+ ? issued.mcpServiceToken.expiresAt.toISOString()
221
+ : null,
222
+ id: String(issued.mcpServiceToken._id),
223
+ mcpUrl: resolveMcpUrl(req, options.publicMcpUrl),
224
+ name: issued.mcpServiceToken.name,
225
+ token: issued.token,
226
+ tokenPrefix: issued.mcpServiceToken.tokenPrefix,
227
+ };
228
+ },
229
+ method: "POST",
230
+ permissions: [Permissions.IsAuthenticated],
231
+ response: createdTokenResponse,
232
+ summary: "Create an MCP service token",
233
+ tag: ACTION_TAG,
234
+ },
235
+ },
236
+ defaultLimit: DEFAULT_LIST_LIMIT,
237
+ instanceActions: {
238
+ revoke: {
239
+ description:
240
+ "Sets revokedAt on a token owned by the signed-in user. Unknown, foreign, and already revoked tokens are 404.",
241
+ handler: async ({doc, user}) => {
242
+ const owner = requireAuthenticatedUser(user);
243
+ const token = doc as McpServiceTokenDocument;
244
+ if (String(token.userId) !== String(owner._id)) {
245
+ throw new NotFoundError("MCP service token not found");
246
+ }
247
+ const revoked = await McpServiceToken.revokeForUser({_id: owner._id}, token._id);
248
+ if (!revoked) {
249
+ throw new NotFoundError("MCP service token not found");
250
+ }
251
+ return toPublicMcpServiceToken(revoked.toObject() as Record<string, unknown>);
252
+ },
253
+ method: "POST",
254
+ permissions: [Permissions.IsAuthenticated],
255
+ summary: "Revoke an MCP service token",
256
+ tag: ACTION_TAG,
257
+ },
258
+ },
259
+ maxLimit: MAX_LIST_LIMIT,
260
+ openApi: options.openApi,
261
+ permissions: {
262
+ create: [],
263
+ delete: [],
264
+ list: [Permissions.IsAuthenticated],
265
+ read: [isTokenOwner],
266
+ update: [],
267
+ },
268
+ queryFields: ["_id"],
269
+ queryFilter: async (user?: User) => {
270
+ if (!user?.id) {
271
+ return null;
272
+ }
273
+ // Tokens from before a password reset or session revocation no longer work; drop them
274
+ // before the list.
256
275
  await McpServiceToken.revokeOutdatedForUser({
257
- _id: user._id,
276
+ _id: user.id,
258
277
  tokenEpoch: userTokenEpoch(user),
259
278
  });
260
- const filter = {userId: new mongoose.Types.ObjectId(String(user._id))};
261
- const total = await McpServiceToken.countDocuments(filter);
262
- const docs = await McpServiceToken.find(filter)
263
- .sort("-created")
264
- .skip((page - 1) * limit)
265
- .limit(limit + 1);
266
- const more = docs.length > limit;
267
- const pageDocs = more ? docs.slice(0, limit) : docs;
268
- return res.json({
269
- data: pageDocs.map(toListItem),
270
- limit,
271
- more,
272
- page,
273
- total,
274
- });
275
- })
276
- );
279
+ return {userId: user.id};
280
+ },
281
+ responseHandler:
282
+ mcpServiceTokenResponseHandler as ModelRouterOptions<McpServiceTokenDocument>["responseHandler"],
283
+ sort: "-created",
284
+ sync: {
285
+ responseHandler: (doc) => toPublicMcpServiceToken(doc),
286
+ scope: {field: "userId", type: "owner"},
287
+ },
288
+ });
277
289
 
278
- app.delete(
279
- "/mcp/service-tokens/:id",
280
- [
281
- ...serviceTokenGuards,
282
- createOpenApiBuilder(openApiOptions)
283
- .withTags(["mcp"])
284
- .withOperationId("revokeMcpServiceToken")
285
- .withSummary("Revoke an MCP service token")
286
- .withDescription("Sets revokedAt on a token owned by the signed-in user.")
287
- .withPathParameter("id", {type: "string"})
288
- .withResponse(200, {
289
- data: {
290
- properties: {
291
- id: {type: "string"},
292
- revokedAt: {type: "string"},
293
- },
294
- type: "object",
295
- },
296
- })
297
- .build(),
298
- ],
299
- asyncHandler(async (req, res) => {
300
- const user = requireAuthenticatedUser(req);
301
- const tokenId = req.params.id;
302
- if (!mongoose.Types.ObjectId.isValid(tokenId)) {
303
- throw new NotFoundError("MCP service token not found");
304
- }
305
- const revoked = await McpServiceToken.revokeForUser(
306
- {_id: user._id},
307
- new mongoose.Types.ObjectId(tokenId)
308
- );
309
- if (!revoked) {
310
- throw new NotFoundError("MCP service token not found");
311
- }
312
- return res.json({
313
- data: {
314
- id: String(revoked._id),
315
- revokedAt: revoked.revokedAt ? revoked.revokedAt.toISOString() : null,
316
- },
317
- });
318
- })
319
- );
290
+ /**
291
+ * Mount the self-serve MCP service token routes at `/mcp/service-tokens`. Callers must
292
+ * authenticate with a session or JWT; an `mcp_` bearer is rejected so a service token
293
+ * cannot list, mint, or revoke tokens.
294
+ */
295
+ export const addMcpServiceTokenRoutes = (
296
+ app: Application,
297
+ options: McpServiceTokenRoutesOptions = {}
298
+ ): void => {
299
+ const registration = createMcpServiceTokenRouter(options);
300
+ app.use(MCP_SERVICE_TOKENS_ROUTE_PATH, rejectMcpServiceTokenBearer, registration.router);
320
301
  };
@@ -3,23 +3,23 @@ import {Writable} from "node:stream";
3
3
  import * as Sentry from "@sentry/bun";
4
4
  import mongoose, {Schema} from "mongoose";
5
5
  import winston from "winston";
6
-
6
+ import type {User} from "../auth";
7
7
  import {winstonLogger} from "../logger";
8
8
  import {Permissions} from "../permissions";
9
9
  import {getCurrentRequestContext, runWithRequestContext} from "../requestContext";
10
10
  import {generateAllTools, generateToolsForEntry} from "./toolGenerator";
11
11
  import type {MCPRegistryEntry} from "./types";
12
12
 
13
- const createTestModel = () => {
13
+ const createTestModel = (): mongoose.Model<unknown> => {
14
14
  try {
15
- return mongoose.model("MCPToolGenTest");
15
+ return mongoose.model<unknown>("MCPToolGenTest");
16
16
  } catch {
17
17
  const schema = new Schema({
18
18
  completed: {default: false, description: "Whether the item is complete", type: Boolean},
19
19
  name: {description: "The name", required: true, type: String},
20
20
  ownerId: {description: "Owner", ref: "User", type: Schema.Types.ObjectId},
21
21
  });
22
- return mongoose.model("MCPToolGenTest", schema);
22
+ return mongoose.model<unknown>("MCPToolGenTest", schema);
23
23
  }
24
24
  };
25
25
 
@@ -264,7 +264,11 @@ describe("tool-call observability", () => {
264
264
  },
265
265
  });
266
266
  const [tool] = generateToolsForEntry(entry);
267
- const user = {_id: new mongoose.Types.ObjectId(), admin: false, id: "user-123"};
267
+ const user: User = {
268
+ _id: new mongoose.Types.ObjectId() as unknown as User["_id"],
269
+ admin: false,
270
+ id: "user-123",
271
+ };
268
272
 
269
273
  await runWithRequestContext({}, async () => {
270
274
  const result = await tool.handler({}, user);