@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
|
@@ -1,20 +1,22 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
-
};
|
|
5
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.addMcpServiceTokenRoutes = exports.resolveMcpServiceTokensOption = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = void 0;
|
|
3
|
+
exports.addMcpServiceTokenRoutes = exports.createMcpServiceTokenRouter = exports.toPublicMcpServiceToken = exports.resolveMcpServiceTokensOption = exports.MCP_SERVICE_TOKENS_SYNC_COLLECTION = exports.MCP_SERVICE_TOKENS_ROUTE_PATH = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = void 0;
|
|
7
4
|
const luxon_1 = require("luxon");
|
|
8
|
-
const mongoose_1 = __importDefault(require("mongoose"));
|
|
9
5
|
const api_1 = require("../api");
|
|
10
|
-
const auth_1 = require("../auth");
|
|
11
6
|
const errors_1 = require("../errors");
|
|
12
7
|
const mcpServiceToken_1 = require("../models/mcpServiceToken");
|
|
13
|
-
const
|
|
14
|
-
const
|
|
8
|
+
const permissions_1 = require("../permissions");
|
|
9
|
+
const transformers_1 = require("../transformers");
|
|
10
|
+
const zodOpenApi_1 = require("../zodOpenApi");
|
|
11
|
+
const auth_1 = require("./auth");
|
|
15
12
|
exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = 10;
|
|
13
|
+
/** Route path of the self-serve MCP service token router. */
|
|
14
|
+
exports.MCP_SERVICE_TOKENS_ROUTE_PATH = "/mcp/service-tokens";
|
|
15
|
+
/** Sync collection tag clients subscribe to (`mcp/service-tokens|owner:{userId}`). */
|
|
16
|
+
exports.MCP_SERVICE_TOKENS_SYNC_COLLECTION = "mcp/service-tokens";
|
|
16
17
|
const DEFAULT_LIST_LIMIT = 100;
|
|
17
18
|
const MAX_LIST_LIMIT = 100;
|
|
19
|
+
const ACTION_TAG = "mcpServiceTokens";
|
|
18
20
|
const resolveMcpServiceTokensOption = (option) => {
|
|
19
21
|
if (option === true) {
|
|
20
22
|
return { enabled: true };
|
|
@@ -43,17 +45,13 @@ const rejectMcpServiceTokenBearer = (req, _res, next) => {
|
|
|
43
45
|
}
|
|
44
46
|
next();
|
|
45
47
|
};
|
|
46
|
-
const requireAuthenticatedUser = (
|
|
47
|
-
const user = req.user;
|
|
48
|
+
const requireAuthenticatedUser = (user) => {
|
|
48
49
|
if (!user?._id) {
|
|
49
50
|
throw new errors_1.UnauthorizedError("Unauthorized");
|
|
50
51
|
}
|
|
51
52
|
return user;
|
|
52
53
|
};
|
|
53
54
|
const parseName = (value) => {
|
|
54
|
-
if (typeof value !== "string") {
|
|
55
|
-
throw new errors_1.BadRequestError({ title: "name is required" });
|
|
56
|
-
}
|
|
57
55
|
const name = value.trim();
|
|
58
56
|
if (!name) {
|
|
59
57
|
throw new errors_1.BadRequestError({ title: "name is required" });
|
|
@@ -64,9 +62,6 @@ const parseExpiresAt = (value) => {
|
|
|
64
62
|
if (value === undefined || value === null || value === "") {
|
|
65
63
|
return undefined;
|
|
66
64
|
}
|
|
67
|
-
if (typeof value !== "string") {
|
|
68
|
-
throw new errors_1.BadRequestError({ title: "expiresAt must be an ISO-8601 datetime string" });
|
|
69
|
-
}
|
|
70
65
|
const parsed = luxon_1.DateTime.fromISO(value, { setZone: true });
|
|
71
66
|
if (!parsed.isValid) {
|
|
72
67
|
throw new errors_1.BadRequestError({ title: "expiresAt must be an ISO-8601 datetime string" });
|
|
@@ -76,26 +71,6 @@ const parseExpiresAt = (value) => {
|
|
|
76
71
|
}
|
|
77
72
|
return parsed.toUTC().toJSDate();
|
|
78
73
|
};
|
|
79
|
-
const parsePage = (value) => {
|
|
80
|
-
if (value === undefined) {
|
|
81
|
-
return 1;
|
|
82
|
-
}
|
|
83
|
-
const page = Number(value);
|
|
84
|
-
if (!Number.isInteger(page) || page < 1) {
|
|
85
|
-
throw new errors_1.BadRequestError({ code: "invalid-page", title: "Invalid page" });
|
|
86
|
-
}
|
|
87
|
-
return page;
|
|
88
|
-
};
|
|
89
|
-
const parseLimit = (value) => {
|
|
90
|
-
if (value === undefined) {
|
|
91
|
-
return DEFAULT_LIST_LIMIT;
|
|
92
|
-
}
|
|
93
|
-
const limit = Number(value);
|
|
94
|
-
if (!Number.isInteger(limit) || limit < 1) {
|
|
95
|
-
throw new errors_1.BadRequestError({ title: "Invalid limit" });
|
|
96
|
-
}
|
|
97
|
-
return Math.min(limit, MAX_LIST_LIMIT);
|
|
98
|
-
};
|
|
99
74
|
const resolveMcpUrl = (req, publicMcpUrl) => {
|
|
100
75
|
const configured = publicMcpUrl ?? process.env.BETTER_AUTH_URL;
|
|
101
76
|
if (configured) {
|
|
@@ -108,159 +83,160 @@ const resolveMcpUrl = (req, publicMcpUrl) => {
|
|
|
108
83
|
const host = req.get("host") ?? "localhost";
|
|
109
84
|
return `${req.protocol}://${host}/mcp`;
|
|
110
85
|
};
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
revokedAt: doc.revokedAt ? doc.revokedAt.toISOString() : null,
|
|
119
|
-
tokenPrefix: doc.tokenPrefix,
|
|
120
|
-
};
|
|
86
|
+
/**
|
|
87
|
+
* Public shape of a stored MCP service token: every field except `tokenHash`, plus `id`.
|
|
88
|
+
* Used for REST responses, sync snapshots, and sync deltas so the hash never leaves the server.
|
|
89
|
+
*/
|
|
90
|
+
const toPublicMcpServiceToken = (doc) => {
|
|
91
|
+
const { tokenHash: _tokenHash, ...rest } = doc;
|
|
92
|
+
return { ...rest, id: String(doc._id) };
|
|
121
93
|
};
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
94
|
+
exports.toPublicMcpServiceToken = toPublicMcpServiceToken;
|
|
95
|
+
const stripTokenHash = (value) => {
|
|
96
|
+
if (Array.isArray(value)) {
|
|
97
|
+
return value.map(stripTokenHash);
|
|
98
|
+
}
|
|
99
|
+
if (value && typeof value === "object") {
|
|
100
|
+
const { tokenHash: _tokenHash, ...rest } = value;
|
|
101
|
+
return rest;
|
|
102
|
+
}
|
|
103
|
+
return value;
|
|
131
104
|
};
|
|
132
|
-
const
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
105
|
+
const mcpServiceTokenResponseHandler = async (value, method, req, options) => {
|
|
106
|
+
const serialized = await (0, transformers_1.defaultResponseHandler)(value, method, req, options);
|
|
107
|
+
return stripTokenHash(serialized);
|
|
108
|
+
};
|
|
109
|
+
/** Read access is owner-only (no admin bypass: admins use the admin panel). */
|
|
110
|
+
const isTokenOwner = (_method, user, obj) => {
|
|
111
|
+
if (!user?.id) {
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
if (!obj) {
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
return String(obj.userId) === String(user.id);
|
|
118
|
+
};
|
|
119
|
+
const createBody = zodOpenApi_1.z.object({
|
|
120
|
+
expiresAt: zodOpenApi_1.z
|
|
121
|
+
.string()
|
|
122
|
+
.nullable()
|
|
123
|
+
.optional()
|
|
124
|
+
.describe("Optional ISO-8601 expiry; omit for a token that does not expire"),
|
|
125
|
+
name: zodOpenApi_1.z.string().describe("User-visible label for this token"),
|
|
126
|
+
});
|
|
127
|
+
const createdTokenResponse = zodOpenApi_1.z.object({
|
|
128
|
+
created: zodOpenApi_1.z.string(),
|
|
129
|
+
expiresAt: zodOpenApi_1.z.string().nullable(),
|
|
130
|
+
id: zodOpenApi_1.z.string(),
|
|
131
|
+
mcpUrl: zodOpenApi_1.z.string(),
|
|
132
|
+
name: zodOpenApi_1.z.string(),
|
|
133
|
+
token: zodOpenApi_1.z.string().describe("The plaintext mcp_ token. Returned only by this response."),
|
|
134
|
+
tokenPrefix: zodOpenApi_1.z.string(),
|
|
135
|
+
});
|
|
136
|
+
/**
|
|
137
|
+
* Build the self-serve `/mcp/service-tokens` router. The collection is synced read-only
|
|
138
|
+
* (owner scope on `userId`): list/read over REST and sync, no client create/update/delete.
|
|
139
|
+
* Minting and revoking are the `create` collection action and `revoke` instance action.
|
|
140
|
+
*/
|
|
141
|
+
const createMcpServiceTokenRouter = (options = {}) => (0, api_1.modelRouter)(exports.MCP_SERVICE_TOKENS_ROUTE_PATH, mcpServiceToken_1.McpServiceToken, {
|
|
142
|
+
collectionActions: {
|
|
143
|
+
create: {
|
|
144
|
+
body: createBody,
|
|
145
|
+
description: "Mints a personal MCP service token that acts as the signed-in user on POST /mcp. The plaintext token is returned once.",
|
|
146
|
+
handler: async ({ body, req, user }) => {
|
|
147
|
+
const owner = requireAuthenticatedUser(user);
|
|
148
|
+
const { expiresAt: rawExpiresAt, name: rawName } = body;
|
|
149
|
+
const name = parseName(rawName);
|
|
150
|
+
const expiresAt = parseExpiresAt(rawExpiresAt);
|
|
151
|
+
await mcpServiceToken_1.McpServiceToken.revokeOutdatedForUser({
|
|
152
|
+
_id: owner._id,
|
|
153
|
+
tokenEpoch: (0, auth_1.userTokenEpoch)(owner),
|
|
154
|
+
});
|
|
155
|
+
const activeCount = await mcpServiceToken_1.McpServiceToken.countActiveForUser(String(owner._id));
|
|
156
|
+
if (activeCount >= exports.MAX_ACTIVE_MCP_SERVICE_TOKENS) {
|
|
157
|
+
throw new errors_1.BadRequestError({
|
|
158
|
+
title: `Maximum of ${exports.MAX_ACTIVE_MCP_SERVICE_TOKENS} active MCP service tokens`,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const issued = await mcpServiceToken_1.McpServiceToken.issueFor({ _id: owner._id, tokenEpoch: (0, auth_1.userTokenEpoch)(owner) }, { expiresAt, name });
|
|
162
|
+
return {
|
|
163
|
+
created: issued.mcpServiceToken.created.toISOString(),
|
|
164
|
+
expiresAt: issued.mcpServiceToken.expiresAt
|
|
165
|
+
? issued.mcpServiceToken.expiresAt.toISOString()
|
|
166
|
+
: null,
|
|
167
|
+
id: String(issued.mcpServiceToken._id),
|
|
168
|
+
mcpUrl: resolveMcpUrl(req, options.publicMcpUrl),
|
|
169
|
+
name: issued.mcpServiceToken.name,
|
|
170
|
+
token: issued.token,
|
|
171
|
+
tokenPrefix: issued.mcpServiceToken.tokenPrefix,
|
|
172
|
+
};
|
|
150
173
|
},
|
|
151
|
-
|
|
152
|
-
.
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
174
|
+
method: "POST",
|
|
175
|
+
permissions: [permissions_1.Permissions.IsAuthenticated],
|
|
176
|
+
response: createdTokenResponse,
|
|
177
|
+
summary: "Create an MCP service token",
|
|
178
|
+
tag: ACTION_TAG,
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
defaultLimit: DEFAULT_LIST_LIMIT,
|
|
182
|
+
instanceActions: {
|
|
183
|
+
revoke: {
|
|
184
|
+
description: "Sets revokedAt on a token owned by the signed-in user. Unknown, foreign, and already revoked tokens are 404.",
|
|
185
|
+
handler: async ({ doc, user }) => {
|
|
186
|
+
const owner = requireAuthenticatedUser(user);
|
|
187
|
+
const token = doc;
|
|
188
|
+
if (String(token.userId) !== String(owner._id)) {
|
|
189
|
+
throw new errors_1.NotFoundError("MCP service token not found");
|
|
190
|
+
}
|
|
191
|
+
const revoked = await mcpServiceToken_1.McpServiceToken.revokeForUser({ _id: owner._id }, token._id);
|
|
192
|
+
if (!revoked) {
|
|
193
|
+
throw new errors_1.NotFoundError("MCP service token not found");
|
|
194
|
+
}
|
|
195
|
+
return (0, exports.toPublicMcpServiceToken)(revoked.toObject());
|
|
156
196
|
},
|
|
157
|
-
|
|
158
|
-
.
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
197
|
+
method: "POST",
|
|
198
|
+
permissions: [permissions_1.Permissions.IsAuthenticated],
|
|
199
|
+
summary: "Revoke an MCP service token",
|
|
200
|
+
tag: ACTION_TAG,
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
maxLimit: MAX_LIST_LIMIT,
|
|
204
|
+
openApi: options.openApi,
|
|
205
|
+
permissions: {
|
|
206
|
+
create: [],
|
|
207
|
+
delete: [],
|
|
208
|
+
list: [permissions_1.Permissions.IsAuthenticated],
|
|
209
|
+
read: [isTokenOwner],
|
|
210
|
+
update: [],
|
|
211
|
+
},
|
|
212
|
+
queryFields: ["_id"],
|
|
213
|
+
queryFilter: async (user) => {
|
|
214
|
+
if (!user?.id) {
|
|
215
|
+
return null;
|
|
172
216
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
data: {
|
|
176
|
-
created: issued.mcpServiceToken.created.toISOString(),
|
|
177
|
-
expiresAt: issued.mcpServiceToken.expiresAt
|
|
178
|
-
? issued.mcpServiceToken.expiresAt.toISOString()
|
|
179
|
-
: null,
|
|
180
|
-
id: String(issued.mcpServiceToken._id),
|
|
181
|
-
mcpUrl: resolveMcpUrl(req, options.publicMcpUrl),
|
|
182
|
-
name: issued.mcpServiceToken.name,
|
|
183
|
-
token: issued.token,
|
|
184
|
-
tokenPrefix: issued.mcpServiceToken.tokenPrefix,
|
|
185
|
-
},
|
|
186
|
-
});
|
|
187
|
-
}));
|
|
188
|
-
app.get("/mcp/service-tokens", [
|
|
189
|
-
...serviceTokenGuards,
|
|
190
|
-
(0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
|
|
191
|
-
.withTags(["mcp"])
|
|
192
|
-
.withOperationId("listMcpServiceTokens")
|
|
193
|
-
.withSummary("List MCP service tokens")
|
|
194
|
-
.withDescription("Lists MCP service tokens owned by the signed-in user. Never includes plaintext or tokenHash.")
|
|
195
|
-
.withQueryParameter("page", { type: "number" }, { required: false })
|
|
196
|
-
.withQueryParameter("limit", { type: "number" }, { required: false })
|
|
197
|
-
.withResponse(200, {
|
|
198
|
-
data: { type: "array" },
|
|
199
|
-
limit: { type: "number" },
|
|
200
|
-
more: { type: "boolean" },
|
|
201
|
-
page: { type: "number" },
|
|
202
|
-
total: { type: "number" },
|
|
203
|
-
})
|
|
204
|
-
.build(),
|
|
205
|
-
], (0, api_1.asyncHandler)(async (req, res) => {
|
|
206
|
-
const user = requireAuthenticatedUser(req);
|
|
207
|
-
const page = parsePage(req.query.page);
|
|
208
|
-
const limit = parseLimit(req.query.limit);
|
|
209
|
-
// Tokens from before a password reset or session revocation no longer work; list them so.
|
|
217
|
+
// Tokens from before a password reset or session revocation no longer work; drop them
|
|
218
|
+
// before the list.
|
|
210
219
|
await mcpServiceToken_1.McpServiceToken.revokeOutdatedForUser({
|
|
211
|
-
_id: user.
|
|
212
|
-
tokenEpoch: (0,
|
|
220
|
+
_id: user.id,
|
|
221
|
+
tokenEpoch: (0, auth_1.userTokenEpoch)(user),
|
|
213
222
|
});
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
(0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
|
|
233
|
-
.withTags(["mcp"])
|
|
234
|
-
.withOperationId("revokeMcpServiceToken")
|
|
235
|
-
.withSummary("Revoke an MCP service token")
|
|
236
|
-
.withDescription("Sets revokedAt on a token owned by the signed-in user.")
|
|
237
|
-
.withPathParameter("id", { type: "string" })
|
|
238
|
-
.withResponse(200, {
|
|
239
|
-
data: {
|
|
240
|
-
properties: {
|
|
241
|
-
id: { type: "string" },
|
|
242
|
-
revokedAt: { type: "string" },
|
|
243
|
-
},
|
|
244
|
-
type: "object",
|
|
245
|
-
},
|
|
246
|
-
})
|
|
247
|
-
.build(),
|
|
248
|
-
], (0, api_1.asyncHandler)(async (req, res) => {
|
|
249
|
-
const user = requireAuthenticatedUser(req);
|
|
250
|
-
const tokenId = req.params.id;
|
|
251
|
-
if (!mongoose_1.default.Types.ObjectId.isValid(tokenId)) {
|
|
252
|
-
throw new errors_1.NotFoundError("MCP service token not found");
|
|
253
|
-
}
|
|
254
|
-
const revoked = await mcpServiceToken_1.McpServiceToken.revokeForUser({ _id: user._id }, new mongoose_1.default.Types.ObjectId(tokenId));
|
|
255
|
-
if (!revoked) {
|
|
256
|
-
throw new errors_1.NotFoundError("MCP service token not found");
|
|
257
|
-
}
|
|
258
|
-
return res.json({
|
|
259
|
-
data: {
|
|
260
|
-
id: String(revoked._id),
|
|
261
|
-
revokedAt: revoked.revokedAt ? revoked.revokedAt.toISOString() : null,
|
|
262
|
-
},
|
|
263
|
-
});
|
|
264
|
-
}));
|
|
223
|
+
return { userId: user.id };
|
|
224
|
+
},
|
|
225
|
+
responseHandler: mcpServiceTokenResponseHandler,
|
|
226
|
+
sort: "-created",
|
|
227
|
+
sync: {
|
|
228
|
+
responseHandler: (doc) => (0, exports.toPublicMcpServiceToken)(doc),
|
|
229
|
+
scope: { field: "userId", type: "owner" },
|
|
230
|
+
},
|
|
231
|
+
});
|
|
232
|
+
exports.createMcpServiceTokenRouter = createMcpServiceTokenRouter;
|
|
233
|
+
/**
|
|
234
|
+
* Mount the self-serve MCP service token routes at `/mcp/service-tokens`. Callers must
|
|
235
|
+
* authenticate with a session or JWT; an `mcp_` bearer is rejected so a service token
|
|
236
|
+
* cannot list, mint, or revoke tokens.
|
|
237
|
+
*/
|
|
238
|
+
const addMcpServiceTokenRoutes = (app, options = {}) => {
|
|
239
|
+
const registration = (0, exports.createMcpServiceTokenRouter)(options);
|
|
240
|
+
app.use(exports.MCP_SERVICE_TOKENS_ROUTE_PATH, rejectMcpServiceTokenBearer, registration.router);
|
|
265
241
|
};
|
|
266
242
|
exports.addMcpServiceTokenRoutes = addMcpServiceTokenRoutes;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { MigrationContext } from "../types";
|
|
2
|
+
export declare const MCP_SERVICE_TOKEN_STRING_IDS_SLUG = "mcp-service-token-string-ids";
|
|
3
|
+
export interface McpServiceTokenStringIdsResult {
|
|
4
|
+
/** Rows re-keyed to a String `_id` in this run. */
|
|
5
|
+
converted: number;
|
|
6
|
+
/** ObjectId-keyed rows still waiting (non-zero only for dry runs). */
|
|
7
|
+
pending: number;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Re-key every ObjectId McpServiceToken row to its hex string. Returns how many rows were
|
|
11
|
+
* converted; a dry run converts nothing and reports how many are pending.
|
|
12
|
+
*/
|
|
13
|
+
export declare const migrateMcpServiceTokenStringIds: (ctx: MigrationContext) => Promise<McpServiceTokenStringIdsResult>;
|
|
14
|
+
/** Ready-made `up` for an app migration file (irreversible: new rows use UUID ids). */
|
|
15
|
+
export declare const mcpServiceTokenStringIdsMigration: {
|
|
16
|
+
slug: string;
|
|
17
|
+
up: (ctx: MigrationContext) => Promise<void>;
|
|
18
|
+
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mcpServiceTokenStringIdsMigration = exports.migrateMcpServiceTokenStringIds = exports.MCP_SERVICE_TOKEN_STRING_IDS_SLUG = void 0;
|
|
4
|
+
exports.MCP_SERVICE_TOKEN_STRING_IDS_SLUG = "mcp-service-token-string-ids";
|
|
5
|
+
const COLLECTION_NAME = "mcpservicetokens";
|
|
6
|
+
const BATCH_SIZE = 200;
|
|
7
|
+
const PARKED_HASH_PREFIX = "mcp-service-token-string-ids:";
|
|
8
|
+
const LEGACY_ID_FILTER = { _id: { $type: "objectId" } };
|
|
9
|
+
const unparkedHash = (tokenHash) => tokenHash.startsWith(PARKED_HASH_PREFIX) ? tokenHash.slice(PARKED_HASH_PREFIX.length) : tokenHash;
|
|
10
|
+
const convertRow = async ({ collection, row, }) => {
|
|
11
|
+
const stringId = row._id.toHexString();
|
|
12
|
+
const tokenHash = unparkedHash(row.tokenHash);
|
|
13
|
+
const parkedHash = `${PARKED_HASH_PREFIX}${tokenHash}`;
|
|
14
|
+
// Free the unique tokenHash for the copy while keeping the original row recoverable.
|
|
15
|
+
if (row.tokenHash !== parkedHash) {
|
|
16
|
+
await collection.updateOne({ _id: row._id }, { $set: { tokenHash: parkedHash } });
|
|
17
|
+
}
|
|
18
|
+
const existingCopy = await collection.findOne({ _id: stringId });
|
|
19
|
+
if (!existingCopy) {
|
|
20
|
+
await collection.insertOne({
|
|
21
|
+
...row,
|
|
22
|
+
_id: stringId,
|
|
23
|
+
deleted: row.deleted ?? false,
|
|
24
|
+
tokenHash,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
await collection.deleteOne({ _id: row._id });
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* Re-key every ObjectId McpServiceToken row to its hex string. Returns how many rows were
|
|
31
|
+
* converted; a dry run converts nothing and reports how many are pending.
|
|
32
|
+
*/
|
|
33
|
+
const migrateMcpServiceTokenStringIds = async (ctx) => {
|
|
34
|
+
const collection = ctx.mongoose.connection.collection(COLLECTION_NAME);
|
|
35
|
+
if (ctx.dryRun) {
|
|
36
|
+
const pending = await collection.countDocuments(LEGACY_ID_FILTER);
|
|
37
|
+
ctx.logger.info(`[${exports.MCP_SERVICE_TOKEN_STRING_IDS_SLUG}] dry run: ${pending} ObjectId rows would be re-keyed`);
|
|
38
|
+
return { converted: 0, pending };
|
|
39
|
+
}
|
|
40
|
+
let converted = 0;
|
|
41
|
+
for (;;) {
|
|
42
|
+
await ctx.checkCancellation?.();
|
|
43
|
+
const batch = (await collection
|
|
44
|
+
.find(LEGACY_ID_FILTER)
|
|
45
|
+
.limit(BATCH_SIZE)
|
|
46
|
+
.toArray());
|
|
47
|
+
if (batch.length === 0) {
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
for (const row of batch) {
|
|
51
|
+
await convertRow({ collection, row });
|
|
52
|
+
converted += 1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const message = `[${exports.MCP_SERVICE_TOKEN_STRING_IDS_SLUG}] re-keyed ${converted} rows to String ids`;
|
|
56
|
+
ctx.logger.info(message);
|
|
57
|
+
await ctx.addLog?.("info", message);
|
|
58
|
+
return { converted, pending: 0 };
|
|
59
|
+
};
|
|
60
|
+
exports.migrateMcpServiceTokenStringIds = migrateMcpServiceTokenStringIds;
|
|
61
|
+
/** Ready-made `up` for an app migration file (irreversible: new rows use UUID ids). */
|
|
62
|
+
exports.mcpServiceTokenStringIdsMigration = {
|
|
63
|
+
slug: exports.MCP_SERVICE_TOKEN_STRING_IDS_SLUG,
|
|
64
|
+
up: async (ctx) => {
|
|
65
|
+
await (0, exports.migrateMcpServiceTokenStringIds)(ctx);
|
|
66
|
+
},
|
|
67
|
+
};
|
|
@@ -144,6 +144,17 @@ mcpOAuthTokenSchema.statics = {
|
|
|
144
144
|
refreshToken: includeRefreshToken ? refreshSecret : undefined,
|
|
145
145
|
};
|
|
146
146
|
},
|
|
147
|
+
async revokeAllForUser(userId) {
|
|
148
|
+
const tokens = await this.find({
|
|
149
|
+
revokedAt: { $exists: false },
|
|
150
|
+
userId: new mongoose_1.default.Types.ObjectId(String(userId)),
|
|
151
|
+
}).select({ familyId: 1 });
|
|
152
|
+
const familyIds = new Set(tokens.map((token) => token.familyId));
|
|
153
|
+
for (const familyId of familyIds) {
|
|
154
|
+
await this.revokeFamily(familyId);
|
|
155
|
+
}
|
|
156
|
+
return familyIds.size;
|
|
157
|
+
},
|
|
147
158
|
async revokeClient(clientId) {
|
|
148
159
|
const tokens = await this.find({ clientId, revokedAt: { $exists: false } }).select({ familyId: 1 });
|
|
149
160
|
const familyIds = new Set(tokens.map((token) => token.familyId));
|
|
@@ -179,5 +190,21 @@ mcpOAuthTokenSchema.statics = {
|
|
|
179
190
|
});
|
|
180
191
|
},
|
|
181
192
|
};
|
|
193
|
+
// Deleting a token row (for example from the admin panel) revokes its whole rotation chain and
|
|
194
|
+
// keeps the rows, so the connection ends and its history stays visible.
|
|
195
|
+
mcpOAuthTokenSchema.methods = {
|
|
196
|
+
...mcpOAuthTokenSchema.methods,
|
|
197
|
+
async deleteOne() {
|
|
198
|
+
await this.constructor.revokeFamily(this.familyId);
|
|
199
|
+
return this;
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
mcpOAuthTokenSchema.pre("deleteOne", { document: false, query: true }, async function () {
|
|
203
|
+
const [existing] = await this.model.find(this.getFilter()).limit(1).select({ familyId: 1 });
|
|
204
|
+
if (existing) {
|
|
205
|
+
await this.model.revokeFamily(existing.familyId);
|
|
206
|
+
}
|
|
207
|
+
this.setQuery({ _id: { $exists: false } });
|
|
208
|
+
});
|
|
182
209
|
exports.McpOAuthToken = mongoose_1.default.models.TerrenoMcpOAuthToken ??
|
|
183
210
|
mongoose_1.default.model("TerrenoMcpOAuthToken", mcpOAuthTokenSchema, "mcpoauthtokens");
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.McpRequestLog = void 0;
|
|
7
|
+
const mongoose_1 = __importDefault(require("mongoose"));
|
|
8
|
+
const plugins_1 = require("../plugins");
|
|
9
|
+
/**
|
|
10
|
+
* One row per MCP tool call when `mcpRequestLog` is on. Metadata only: tool arguments, results,
|
|
11
|
+
* and error messages are never stored. Rows expire at `expiresAt`.
|
|
12
|
+
*/
|
|
13
|
+
const mcpRequestLogSchema = new mongoose_1.default.Schema({
|
|
14
|
+
credential: {
|
|
15
|
+
description: "Credential type that authenticated the call",
|
|
16
|
+
enum: ["jwt", "better-auth-session", "mcp-service-token", "oauth"],
|
|
17
|
+
type: String,
|
|
18
|
+
},
|
|
19
|
+
durationMs: {
|
|
20
|
+
description: "Time the tool handler took, in milliseconds",
|
|
21
|
+
required: true,
|
|
22
|
+
type: Number,
|
|
23
|
+
},
|
|
24
|
+
errorName: {
|
|
25
|
+
description: "Error class name when the tool threw; never the error message",
|
|
26
|
+
type: String,
|
|
27
|
+
},
|
|
28
|
+
expiresAt: {
|
|
29
|
+
description: "When this log row is removed",
|
|
30
|
+
required: true,
|
|
31
|
+
type: Date,
|
|
32
|
+
},
|
|
33
|
+
oauthClientId: {
|
|
34
|
+
description: "OAuth client id when the call used an MCP OAuth access token",
|
|
35
|
+
index: true,
|
|
36
|
+
type: String,
|
|
37
|
+
},
|
|
38
|
+
oauthFamilyId: {
|
|
39
|
+
description: "OAuth token family (one approved connection) when the call used OAuth",
|
|
40
|
+
type: String,
|
|
41
|
+
},
|
|
42
|
+
outcome: {
|
|
43
|
+
description: "ok, tool_error (the tool returned isError), or exception (the tool threw)",
|
|
44
|
+
enum: ["ok", "tool_error", "exception"],
|
|
45
|
+
required: true,
|
|
46
|
+
type: String,
|
|
47
|
+
},
|
|
48
|
+
serviceTokenId: {
|
|
49
|
+
description: "Service token used for the call, when the credential was a service token",
|
|
50
|
+
index: true,
|
|
51
|
+
ref: "TerrenoMcpServiceToken",
|
|
52
|
+
type: String,
|
|
53
|
+
},
|
|
54
|
+
toolName: {
|
|
55
|
+
description: "Name of the MCP tool that was called",
|
|
56
|
+
index: true,
|
|
57
|
+
required: true,
|
|
58
|
+
type: String,
|
|
59
|
+
},
|
|
60
|
+
userId: {
|
|
61
|
+
description: "User the call acted as",
|
|
62
|
+
index: true,
|
|
63
|
+
ref: "User",
|
|
64
|
+
type: mongoose_1.default.Schema.Types.ObjectId,
|
|
65
|
+
},
|
|
66
|
+
}, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
|
|
67
|
+
mcpRequestLogSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
|
|
68
|
+
mcpRequestLogSchema.index({ created: -1 });
|
|
69
|
+
mcpRequestLogSchema.plugin(plugins_1.createdUpdatedPlugin);
|
|
70
|
+
mcpRequestLogSchema.plugin(plugins_1.findOneOrNone);
|
|
71
|
+
mcpRequestLogSchema.plugin(plugins_1.findExactlyOne);
|
|
72
|
+
exports.McpRequestLog = mongoose_1.default.models.TerrenoMcpRequestLog ??
|
|
73
|
+
mongoose_1.default.model("TerrenoMcpRequestLog", mcpRequestLogSchema, "mcprequestlogs");
|