@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.
- package/CHANGELOG.md +93 -0
- package/README.md +1 -1
- package/biome.jsonc +3 -2
- package/dist/api.d.ts +3 -16
- package/dist/api.js +0 -9
- package/dist/auth.d.ts +3 -2
- package/dist/auth.js +95 -5
- package/dist/authRecovery.d.ts +2 -1
- package/dist/authRecovery.js +35 -17
- package/dist/collectionRegistry.d.ts +3 -4
- package/dist/collectionRegistry.js +0 -1
- package/dist/consentApp.d.ts +1 -1
- package/dist/consentApp.js +58 -2
- package/dist/frameworkModelNames.d.ts +4 -0
- package/dist/frameworkModelNames.js +4 -0
- package/dist/index.d.ts +8 -5
- package/dist/index.js +14 -20
- package/dist/mcp/adminTracking.d.ts +28 -0
- package/dist/mcp/adminTracking.js +80 -0
- package/dist/mcp/auth.d.ts +6 -0
- package/dist/mcp/auth.js +12 -2
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +48 -4
- package/dist/mcp/serviceTokens.d.ts +21 -1
- package/dist/mcp/serviceTokens.js +159 -183
- package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
- package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
- package/dist/models/mcpOAuthToken.js +27 -0
- package/dist/models/mcpRequestLog.d.ts +2 -0
- package/dist/models/mcpRequestLog.js +73 -0
- package/dist/models/mcpServiceToken.js +40 -4
- package/dist/models/mcpToolSetting.d.ts +2 -0
- package/dist/models/mcpToolSetting.js +119 -0
- package/dist/models/versionConfig.d.ts +2 -0
- package/dist/openApiBuilder.d.ts +4 -0
- package/dist/openApiBuilder.js +2 -0
- package/dist/rbac/auditModel.d.ts +2 -1
- package/dist/rbac/realtimeAccess.d.ts +5 -4
- package/dist/rbac/realtimeAccess.js +17 -64
- package/dist/realtime/changeStreamWatcher.d.ts +8 -63
- package/dist/realtime/changeStreamWatcher.js +32 -391
- package/dist/realtime/realtimeApp.d.ts +14 -27
- package/dist/realtime/realtimeApp.js +14 -220
- package/dist/realtime/types.d.ts +0 -64
- package/dist/sync/executors.js +14 -2
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/socketHandlers.js +1 -1
- package/dist/terrenoApp.d.ts +19 -5
- package/dist/terrenoApp.js +21 -14
- package/dist/tests/models.d.ts +17 -22
- package/dist/tests/models.js +7 -1
- package/dist/tests/openApiResponseSchema.d.ts +39 -0
- package/dist/tests/openApiResponseSchema.js +56 -0
- package/dist/tests/testHelper.d.ts +6 -12
- package/dist/tests.d.ts +2 -0
- package/dist/tests.js +6 -1
- package/dist/types/mcpAdmin.d.ts +58 -0
- package/dist/types/mcpAdmin.js +2 -0
- package/dist/types/mcpOAuth.d.ts +2 -0
- package/dist/types/mcpServiceToken.d.ts +9 -4
- package/dist/versionCheckPlugin.d.ts +1 -1
- package/dist/versionCheckPlugin.js +25 -2
- package/e2e/smoke.ts +193 -0
- package/package.json +14 -8
- package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
- package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
- package/src/__tests__/openApiResponseSchema.test.ts +148 -0
- package/src/__tests__/versionCheckPlugin.test.ts +72 -0
- package/src/adminModelRouter.test.ts +8 -6
- package/src/api.arrayOperations.test.ts +31 -22
- package/src/api.hooks.test.ts +12 -11
- package/src/api.query.test.ts +2 -2
- package/src/api.test.ts +17 -14
- package/src/api.ts +3 -27
- package/src/audit/auditApp.test.ts +1 -1
- package/src/audit/cloudTasksEnqueue.test.ts +19 -14
- package/src/auth.test.ts +21 -7
- package/src/auth.ts +116 -5
- package/src/authOpenApi.test.ts +316 -0
- package/src/authRecovery.test.ts +10 -10
- package/src/authRecovery.ts +47 -19
- package/src/authVerification.test.ts +7 -7
- package/src/betterAuthFeatures.test.ts +3 -2
- package/src/betterAuthLinking.test.ts +3 -1
- package/src/betterAuthOAuthHandoff.test.ts +13 -5
- package/src/betterAuthSetup.test.ts +77 -51
- package/src/collectionRegistry.test.ts +4 -4
- package/src/collectionRegistry.ts +3 -5
- package/src/consentApp.test.ts +98 -0
- package/src/consentApp.ts +67 -2
- package/src/frameworkModelNames.test.ts +8 -0
- package/src/frameworkModelNames.ts +4 -0
- package/src/githubAuth.test.ts +11 -11
- package/src/index.ts +14 -28
- package/src/isolated/migrateCliConnect.isolated.ts +3 -2
- package/src/mcp/actionTools.test.ts +13 -7
- package/src/mcp/adminTracking.test.ts +272 -0
- package/src/mcp/adminTracking.ts +104 -0
- package/src/mcp/auth.test.ts +7 -3
- package/src/mcp/auth.ts +18 -2
- package/src/mcp/oauth.test.ts +13 -13
- package/src/mcp/server.ts +67 -4
- package/src/mcp/serviceTokens.sync.test.ts +230 -0
- package/src/mcp/serviceTokens.test.ts +114 -62
- package/src/mcp/serviceTokens.ts +193 -212
- package/src/mcp/toolGenerator.test.ts +9 -5
- package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
- package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
- package/src/migrations/cli.test.ts +15 -14
- package/src/migrations/cli.ts +1 -1
- package/src/migrations/generate.test.ts +2 -2
- package/src/migrations/load.test.ts +1 -1
- package/src/migrations/lock.test.ts +8 -3
- package/src/migrations/runner.test.ts +16 -5
- package/src/migrations/schemaCatalog.test.ts +4 -1
- package/src/models/mcpOAuthToken.test.ts +42 -0
- package/src/models/mcpOAuthToken.ts +32 -0
- package/src/models/mcpRequestLog.ts +81 -0
- package/src/models/mcpServiceToken.test.ts +75 -5
- package/src/models/mcpServiceToken.ts +61 -14
- package/src/models/mcpToolSetting.test.ts +69 -0
- package/src/models/mcpToolSetting.ts +138 -0
- package/src/models/versionConfig.ts +2 -0
- package/src/notifications/notificationsApp.test.ts +5 -8
- package/src/notifiers/slackWebApi.test.ts +30 -8
- package/src/openApi.test.ts +4 -4
- package/src/openApiBuilder.test.ts +34 -1
- package/src/openApiBuilder.ts +5 -0
- package/src/openApiValidator.test.ts +3 -3
- package/src/orgs/orgPermissions.test.ts +2 -2
- package/src/orgs/orgPlugin.test.ts +4 -3
- package/src/orgs/orgSecurityDefects.test.ts +3 -1
- package/src/orgs/organizationSettings.test.ts +1 -1
- package/src/orgs/orgsApp.test.ts +5 -3
- package/src/permissions.test.ts +2 -2
- package/src/rateLimit/rateLimit.test.ts +25 -10
- package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
- package/src/rbac/assertAllowed.test.ts +1 -1
- package/src/rbac/auditModel.ts +10 -2
- package/src/rbac/realtimeAccess.test.ts +20 -171
- package/src/rbac/realtimeAccess.ts +17 -82
- package/src/rbac/routes.test.ts +1 -1
- package/src/rbac/userWriteGuards.test.ts +8 -5
- package/src/realtime/changeStreamWatcher.ts +43 -506
- package/src/realtime/realtime.test.ts +211 -2547
- package/src/realtime/realtimeApp.ts +16 -295
- package/src/realtime/types.ts +0 -72
- package/src/scrubAdminFields.test.ts +1 -1
- package/src/sync/adminWindowMutation.test.ts +4 -3
- package/src/sync/executors.test.ts +29 -1
- package/src/sync/executors.ts +23 -2
- package/src/sync/scripts/compactTombstones.test.ts +4 -3
- package/src/sync/socketHandlers.ts +1 -1
- package/src/sync/sync.test.ts +1 -1
- package/src/sync/syncPhaseC.test.ts +14 -11
- package/src/sync/syncRoutes.test.ts +8 -8
- package/src/sync/syncSeqPlugin.test.ts +1 -2
- package/src/sync/syncSocket.test.ts +78 -113
- package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
- package/src/terrenoApp.migrations.test.ts +8 -7
- package/src/terrenoApp.ts +38 -18
- package/src/tests/betterAuthStubs.ts +3 -2
- package/src/tests/bunSetup.ts +1 -1
- package/src/tests/models.ts +10 -0
- package/src/tests/openApiResponseSchema.ts +104 -0
- package/src/tests/testEnv.ts +7 -0
- package/src/tests.ts +8 -0
- package/src/types/mcpAdmin.ts +80 -0
- package/src/types/mcpOAuth.ts +5 -0
- package/src/types/mcpServiceToken.ts +12 -4
- package/src/versionCheckPlugin.ts +41 -2
- package/src/webhooks/verifiers/hmac.test.ts +1 -1
- package/tsconfig.typecheck.json +14 -0
- package/dist/realtime/deprecation.d.ts +0 -13
- package/dist/realtime/deprecation.js +0 -31
- package/dist/realtime/queryStore.d.ts +0 -37
- package/dist/realtime/queryStore.js +0 -103
- package/dist/realtime/registry.d.ts +0 -15
- package/dist/realtime/registry.js +0 -52
- package/src/realtime/deprecation.test.ts +0 -60
- package/src/realtime/deprecation.ts +0 -33
- package/src/realtime/queryStore.ts +0 -122
- package/src/realtime/registry.ts +0 -84
package/src/mcp/serviceTokens.ts
CHANGED
|
@@ -1,19 +1,34 @@
|
|
|
1
1
|
import type {Application, NextFunction, Request, Response} from "express";
|
|
2
2
|
import {DateTime} from "luxon";
|
|
3
|
-
import
|
|
3
|
+
import type {Document} from "mongoose";
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
|
|
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 {
|
|
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 = (
|
|
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:
|
|
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:
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
|
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
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
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
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
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.
|
|
276
|
+
_id: user.id,
|
|
258
277
|
tokenEpoch: userTokenEpoch(user),
|
|
259
278
|
});
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
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
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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 = {
|
|
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);
|