@terreno/api 57.21.0 → 58.0.0-beta.2

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 (121) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +1 -1
  3. package/dist/api.d.ts +0 -13
  4. package/dist/api.js +0 -9
  5. package/dist/auth.d.ts +3 -2
  6. package/dist/auth.js +95 -5
  7. package/dist/authRecovery.d.ts +2 -1
  8. package/dist/authRecovery.js +35 -17
  9. package/dist/collectionRegistry.d.ts +3 -4
  10. package/dist/collectionRegistry.js +0 -1
  11. package/dist/consentApp.d.ts +1 -1
  12. package/dist/consentApp.js +58 -2
  13. package/dist/index.d.ts +4 -5
  14. package/dist/index.js +8 -20
  15. package/dist/mcp/adminTracking.js +1 -1
  16. package/dist/mcp/serviceTokens.d.ts +21 -1
  17. package/dist/mcp/serviceTokens.js +159 -183
  18. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  19. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  20. package/dist/models/mcpRequestLog.js +1 -1
  21. package/dist/models/mcpServiceToken.js +36 -4
  22. package/dist/openApiBuilder.d.ts +4 -0
  23. package/dist/openApiBuilder.js +2 -0
  24. package/dist/rbac/realtimeAccess.d.ts +5 -4
  25. package/dist/rbac/realtimeAccess.js +17 -64
  26. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  27. package/dist/realtime/changeStreamWatcher.js +32 -391
  28. package/dist/realtime/realtimeApp.d.ts +14 -27
  29. package/dist/realtime/realtimeApp.js +14 -220
  30. package/dist/realtime/types.d.ts +0 -64
  31. package/dist/sync/entityIds.d.ts +14 -0
  32. package/dist/sync/entityIds.js +17 -0
  33. package/dist/sync/executors.js +14 -2
  34. package/dist/sync/models.d.ts +1 -0
  35. package/dist/sync/models.js +4 -0
  36. package/dist/sync/mutationHandler.js +51 -2
  37. package/dist/sync/routes.js +12 -17
  38. package/dist/sync/socketHandlers.d.ts +1 -1
  39. package/dist/sync/socketHandlers.js +1 -1
  40. package/dist/sync/types.d.ts +8 -0
  41. package/dist/terrenoApp.d.ts +7 -5
  42. package/dist/terrenoApp.js +18 -14
  43. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  44. package/dist/tests/openApiResponseSchema.js +56 -0
  45. package/dist/tests.d.ts +1 -0
  46. package/dist/tests.js +4 -1
  47. package/dist/types/mcpAdmin.d.ts +1 -1
  48. package/dist/types/mcpServiceToken.d.ts +7 -4
  49. package/dist/versionCheckPlugin.d.ts +1 -1
  50. package/dist/versionCheckPlugin.js +25 -2
  51. package/package.json +17 -6
  52. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  53. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  54. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  55. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  56. package/src/api.test.ts +9 -7
  57. package/src/api.ts +0 -24
  58. package/src/auth.ts +116 -5
  59. package/src/authOpenApi.test.ts +316 -0
  60. package/src/authRecovery.ts +47 -19
  61. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  62. package/src/collectionRegistry.ts +3 -5
  63. package/src/consentApp.test.ts +98 -0
  64. package/src/consentApp.ts +67 -2
  65. package/src/index.ts +6 -28
  66. package/src/mcp/actionTools.test.ts +2 -2
  67. package/src/mcp/adminTracking.ts +1 -1
  68. package/src/mcp/auth.test.ts +7 -3
  69. package/src/mcp/oauth.test.ts +12 -12
  70. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  71. package/src/mcp/serviceTokens.test.ts +112 -61
  72. package/src/mcp/serviceTokens.ts +193 -212
  73. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  74. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  75. package/src/models/mcpRequestLog.ts +1 -1
  76. package/src/models/mcpServiceToken.test.ts +52 -5
  77. package/src/models/mcpServiceToken.ts +51 -14
  78. package/src/openApiBuilder.test.ts +34 -1
  79. package/src/openApiBuilder.ts +5 -0
  80. package/src/rateLimit/rateLimit.test.ts +25 -10
  81. package/src/rbac/realtimeAccess.test.ts +20 -172
  82. package/src/rbac/realtimeAccess.ts +17 -82
  83. package/src/realtime/changeStreamWatcher.ts +43 -506
  84. package/src/realtime/realtime.test.ts +205 -2545
  85. package/src/realtime/realtimeApp.ts +16 -295
  86. package/src/realtime/types.ts +0 -72
  87. package/src/sync/entityIds.ts +18 -0
  88. package/src/sync/executors.test.ts +28 -0
  89. package/src/sync/executors.ts +23 -2
  90. package/src/sync/models.ts +6 -0
  91. package/src/sync/mutationHandler.test.ts +84 -0
  92. package/src/sync/mutationHandler.ts +57 -2
  93. package/src/sync/routes.ts +12 -17
  94. package/src/sync/socketHandlers.ts +1 -1
  95. package/src/sync/syncRoutes.test.ts +8 -4
  96. package/src/sync/syncSocket.test.ts +77 -113
  97. package/src/sync/types.ts +9 -0
  98. package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
  99. package/src/terrenoApp.ts +24 -18
  100. package/src/tests/openApiResponseSchema.ts +104 -0
  101. package/src/tests.ts +7 -0
  102. package/src/types/mcpAdmin.ts +1 -1
  103. package/src/types/mcpServiceToken.ts +7 -4
  104. package/src/versionCheckPlugin.ts +41 -2
  105. package/biome.jsonc +0 -22
  106. package/bunfig.toml +0 -10
  107. package/bunfig.unit.toml +0 -3
  108. package/dist/realtime/deprecation.d.ts +0 -13
  109. package/dist/realtime/deprecation.js +0 -31
  110. package/dist/realtime/queryStore.d.ts +0 -37
  111. package/dist/realtime/queryStore.js +0 -103
  112. package/dist/realtime/registry.d.ts +0 -15
  113. package/dist/realtime/registry.js +0 -52
  114. package/e2e/smoke.ts +0 -193
  115. package/src/realtime/deprecation.test.ts +0 -60
  116. package/src/realtime/deprecation.ts +0 -33
  117. package/src/realtime/queryStore.ts +0 -122
  118. package/src/realtime/registry.ts +0 -84
  119. package/tsconfig.json +0 -19
  120. package/tsconfig.typecheck.json +0 -14
  121. package/tsconfig.typedoc.json +0 -13
@@ -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
  };
@@ -0,0 +1,194 @@
1
+ import {afterEach, beforeAll, beforeEach, describe, it} from "bun:test";
2
+ import {createHash, randomUUID} from "node:crypto";
3
+ import {assert} from "chai";
4
+ import {DateTime} from "luxon";
5
+ import mongoose from "mongoose";
6
+
7
+ import {McpServiceToken} from "../../models/mcpServiceToken";
8
+ import {clearSyncRegistry} from "../../sync/registry";
9
+ import {setupDb} from "../../tests";
10
+ import type {MigrationContext, MigrationLogger} from "../types";
11
+ import {
12
+ MCP_SERVICE_TOKEN_STRING_IDS_SLUG,
13
+ mcpServiceTokenStringIdsMigration,
14
+ migrateMcpServiceTokenStringIds,
15
+ } from "./mcpServiceTokenStringIds";
16
+
17
+ const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
18
+
19
+ const silentLogger: MigrationLogger = {
20
+ debug: () => undefined,
21
+ error: () => undefined,
22
+ info: () => undefined,
23
+ warn: () => undefined,
24
+ };
25
+
26
+ const contextFor = (overrides: Partial<MigrationContext> = {}): MigrationContext => ({
27
+ dryRun: false,
28
+ logger: silentLogger,
29
+ mongoose,
30
+ ...overrides,
31
+ });
32
+
33
+ const tokens = (): mongoose.Collection => McpServiceToken.collection;
34
+
35
+ const legacyRow = (
36
+ plaintext: string,
37
+ userId: mongoose.Types.ObjectId,
38
+ extra: Record<string, unknown> = {}
39
+ ): Record<string, unknown> => ({
40
+ _id: new mongoose.Types.ObjectId(),
41
+ created: DateTime.now().minus({day: 3}).toJSDate(),
42
+ name: `Legacy ${plaintext.slice(-4)}`,
43
+ tokenHash: hashToken(plaintext),
44
+ tokenPrefix: plaintext.slice(4, 12),
45
+ updated: DateTime.now().minus({day: 3}).toJSDate(),
46
+ userId,
47
+ ...extra,
48
+ });
49
+
50
+ describe("mcp-service-token-string-ids migration", () => {
51
+ const userId = new mongoose.Types.ObjectId();
52
+ const activePlaintext = `mcp_${"a".repeat(64)}`;
53
+ const revokedPlaintext = `mcp_${"b".repeat(64)}`;
54
+ let active: Record<string, unknown>;
55
+ let revoked: Record<string, unknown>;
56
+
57
+ beforeAll(async () => {
58
+ await setupDb();
59
+ await McpServiceToken.syncIndexes();
60
+ }, 60_000);
61
+
62
+ beforeEach(async () => {
63
+ clearSyncRegistry();
64
+ await tokens().deleteMany({});
65
+ active = legacyRow(activePlaintext, userId);
66
+ revoked = legacyRow(revokedPlaintext, userId, {
67
+ revokedAt: DateTime.now().minus({day: 1}).toJSDate(),
68
+ });
69
+ await tokens().insertMany([active, revoked]);
70
+ });
71
+
72
+ afterEach(async () => {
73
+ await tokens().deleteMany({});
74
+ });
75
+
76
+ it("re-keys ObjectId rows to their hex string and is idempotent", async () => {
77
+ const issued = await McpServiceToken.issueFor({_id: userId}, {name: "Already a string"});
78
+
79
+ const first = await migrateMcpServiceTokenStringIds(contextFor());
80
+ const second = await migrateMcpServiceTokenStringIds(contextFor());
81
+
82
+ assert.deepEqual(first, {converted: 2, pending: 0});
83
+ assert.deepEqual(second, {converted: 0, pending: 0});
84
+ const rows = await tokens().find({}).toArray();
85
+ assert.lengthOf(rows, 3);
86
+ for (const row of rows) {
87
+ assert.isString(row._id);
88
+ }
89
+ assert.equal(await tokens().countDocuments({_id: {$type: "objectId"}}), 0);
90
+
91
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
92
+ const revokedId = (revoked._id as mongoose.Types.ObjectId).toHexString();
93
+ const migratedActive = await tokens().findOne({_id: activeId as never});
94
+ const migratedRevoked = await tokens().findOne({_id: revokedId as never});
95
+ assert.equal(migratedActive?.name, active.name);
96
+ assert.equal(migratedActive?.tokenHash, active.tokenHash);
97
+ assert.equal(String(migratedActive?.userId), String(userId));
98
+ assert.isFalse(migratedActive?.deleted);
99
+ assert.instanceOf(migratedRevoked?.revokedAt, Date);
100
+ assert.equal(await tokens().countDocuments({_id: issued.mcpServiceToken._id as never}), 1);
101
+ });
102
+
103
+ it("keeps migrated tokens verifiable and revocable by their hex id", async () => {
104
+ await migrateMcpServiceTokenStringIds(contextFor());
105
+
106
+ const verified = await McpServiceToken.verify(activePlaintext);
107
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
108
+ assert.equal(verified?._id, activeId);
109
+ assert.isNull(await McpServiceToken.verify(revokedPlaintext));
110
+
111
+ await McpServiceToken.revokeForUser({_id: userId}, activeId);
112
+ assert.isNull(await McpServiceToken.verify(activePlaintext));
113
+ });
114
+
115
+ it("finishes a row an interrupted run already parked and copied", async () => {
116
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
117
+ // Simulate a crash after the hash was parked and the copy inserted, before the delete.
118
+ await tokens().updateOne(
119
+ {_id: active._id as never},
120
+ {$set: {tokenHash: `${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}:${active.tokenHash}`}}
121
+ );
122
+ await tokens().insertOne({...active, _id: activeId as never, deleted: false});
123
+
124
+ const result = await migrateMcpServiceTokenStringIds(contextFor());
125
+
126
+ assert.equal(result.converted, 2);
127
+ assert.equal(await tokens().countDocuments({}), 2);
128
+ const migrated = await tokens().findOne({_id: activeId as never});
129
+ assert.equal(migrated?.tokenHash, active.tokenHash);
130
+ assert.equal((await McpServiceToken.verify(activePlaintext))?._id, activeId);
131
+ });
132
+
133
+ it("re-inserts a parked row whose copy never landed", async () => {
134
+ await tokens().updateOne(
135
+ {_id: active._id as never},
136
+ {$set: {tokenHash: `${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}:${active.tokenHash}`}}
137
+ );
138
+
139
+ await migrateMcpServiceTokenStringIds(contextFor());
140
+
141
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
142
+ const migrated = await tokens().findOne({_id: activeId as never});
143
+ assert.equal(migrated?.tokenHash, active.tokenHash);
144
+ assert.equal(await tokens().countDocuments({}), 2);
145
+ });
146
+
147
+ it("reports pending rows on a dry run without writing", async () => {
148
+ const logs: string[] = [];
149
+ const result = await migrateMcpServiceTokenStringIds(
150
+ contextFor({
151
+ dryRun: true,
152
+ logger: {...silentLogger, info: (message: string) => logs.push(message)},
153
+ })
154
+ );
155
+
156
+ assert.deepEqual(result, {converted: 0, pending: 2});
157
+ assert.equal(await tokens().countDocuments({_id: {$type: "objectId"}}), 2);
158
+ assert.match(logs[0] ?? "", /2 ObjectId rows would be re-keyed/);
159
+ });
160
+
161
+ it("exposes an up function for app migration files that logs progress", async () => {
162
+ const addLogCalls: string[] = [];
163
+ let cancellationChecks = 0;
164
+
165
+ await mcpServiceTokenStringIdsMigration.up(
166
+ contextFor({
167
+ addLog: async (_level, message) => {
168
+ addLogCalls.push(message);
169
+ },
170
+ checkCancellation: async () => {
171
+ cancellationChecks += 1;
172
+ },
173
+ })
174
+ );
175
+
176
+ assert.equal(mcpServiceTokenStringIdsMigration.slug, "mcp-service-token-string-ids");
177
+ assert.equal(await tokens().countDocuments({_id: {$type: "objectId"}}), 0);
178
+ assert.isAbove(cancellationChecks, 0);
179
+ assert.match(addLogCalls[0] ?? "", /re-keyed 2 rows/);
180
+ });
181
+
182
+ it("does nothing when every row already has a string id", async () => {
183
+ await tokens().deleteMany({});
184
+ await tokens().insertOne({
185
+ ...legacyRow(activePlaintext, userId),
186
+ _id: randomUUID() as never,
187
+ });
188
+
189
+ const result = await migrateMcpServiceTokenStringIds(contextFor());
190
+
191
+ assert.deepEqual(result, {converted: 0, pending: 0});
192
+ assert.equal(await tokens().countDocuments({}), 1);
193
+ });
194
+ });