@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.
- package/CHANGELOG.md +89 -0
- package/README.md +1 -1
- package/dist/api.d.ts +0 -13
- 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/index.d.ts +4 -5
- package/dist/index.js +8 -20
- package/dist/mcp/adminTracking.js +1 -1
- 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/mcpRequestLog.js +1 -1
- package/dist/models/mcpServiceToken.js +36 -4
- package/dist/openApiBuilder.d.ts +4 -0
- package/dist/openApiBuilder.js +2 -0
- 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/entityIds.d.ts +14 -0
- package/dist/sync/entityIds.js +17 -0
- package/dist/sync/executors.js +14 -2
- package/dist/sync/models.d.ts +1 -0
- package/dist/sync/models.js +4 -0
- package/dist/sync/mutationHandler.js +51 -2
- package/dist/sync/routes.js +12 -17
- package/dist/sync/socketHandlers.d.ts +1 -1
- package/dist/sync/socketHandlers.js +1 -1
- package/dist/sync/types.d.ts +8 -0
- package/dist/terrenoApp.d.ts +7 -5
- package/dist/terrenoApp.js +18 -14
- package/dist/tests/openApiResponseSchema.d.ts +39 -0
- package/dist/tests/openApiResponseSchema.js +56 -0
- package/dist/tests.d.ts +1 -0
- package/dist/tests.js +4 -1
- package/dist/types/mcpAdmin.d.ts +1 -1
- package/dist/types/mcpServiceToken.d.ts +7 -4
- package/dist/versionCheckPlugin.d.ts +1 -1
- package/dist/versionCheckPlugin.js +25 -2
- package/package.json +17 -6
- 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/api.test.ts +9 -7
- package/src/api.ts +0 -24
- package/src/auth.ts +116 -5
- package/src/authOpenApi.test.ts +316 -0
- package/src/authRecovery.ts +47 -19
- package/src/betterAuthOAuthHandoff.test.ts +13 -5
- package/src/collectionRegistry.ts +3 -5
- package/src/consentApp.test.ts +98 -0
- package/src/consentApp.ts +67 -2
- package/src/index.ts +6 -28
- package/src/mcp/actionTools.test.ts +2 -2
- package/src/mcp/adminTracking.ts +1 -1
- package/src/mcp/auth.test.ts +7 -3
- package/src/mcp/oauth.test.ts +12 -12
- package/src/mcp/serviceTokens.sync.test.ts +230 -0
- package/src/mcp/serviceTokens.test.ts +112 -61
- package/src/mcp/serviceTokens.ts +193 -212
- package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
- package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
- package/src/models/mcpRequestLog.ts +1 -1
- package/src/models/mcpServiceToken.test.ts +52 -5
- package/src/models/mcpServiceToken.ts +51 -14
- package/src/openApiBuilder.test.ts +34 -1
- package/src/openApiBuilder.ts +5 -0
- package/src/rateLimit/rateLimit.test.ts +25 -10
- package/src/rbac/realtimeAccess.test.ts +20 -172
- package/src/rbac/realtimeAccess.ts +17 -82
- package/src/realtime/changeStreamWatcher.ts +43 -506
- package/src/realtime/realtime.test.ts +205 -2545
- package/src/realtime/realtimeApp.ts +16 -295
- package/src/realtime/types.ts +0 -72
- package/src/sync/entityIds.ts +18 -0
- package/src/sync/executors.test.ts +28 -0
- package/src/sync/executors.ts +23 -2
- package/src/sync/models.ts +6 -0
- package/src/sync/mutationHandler.test.ts +84 -0
- package/src/sync/mutationHandler.ts +57 -2
- package/src/sync/routes.ts +12 -17
- package/src/sync/socketHandlers.ts +1 -1
- package/src/sync/syncRoutes.test.ts +8 -4
- package/src/sync/syncSocket.test.ts +77 -113
- package/src/sync/types.ts +9 -0
- package/src/terrenoApp.mcpServiceTokens.test.ts +14 -6
- package/src/terrenoApp.ts +24 -18
- package/src/tests/openApiResponseSchema.ts +104 -0
- package/src/tests.ts +7 -0
- package/src/types/mcpAdmin.ts +1 -1
- package/src/types/mcpServiceToken.ts +7 -4
- package/src/versionCheckPlugin.ts +41 -2
- package/biome.jsonc +0 -22
- package/bunfig.toml +0 -10
- package/bunfig.unit.toml +0 -3
- 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/e2e/smoke.ts +0 -193
- 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/tsconfig.json +0 -19
- package/tsconfig.typecheck.json +0 -14
- package/tsconfig.typedoc.json +0 -13
package/dist/index.js
CHANGED
|
@@ -14,9 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
15
|
};
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
exports.
|
|
18
|
-
exports.
|
|
19
|
-
exports.z = exports.WebhooksApp = exports.twilioSignature = exports.stripeSignature = exports.sendgridEventSignature = exports.hmacSignature = exports.createMemoryIdempotencyStore = exports.stripAdminBodyFields = exports.scrubAdminFields = exports.adminBodyFieldsToStrip = exports.SYSTEM_FIELD_PATHS = exports.nestDottedFieldDescriptions = exports.modelDescriptionToOpenApiSpec = exports.modelDescriptionToAdminFields = exports.fieldDescriptionToZodType = exports.fieldDescriptionToOpenApiProperty = exports.fieldDescriptionToAdminMeta = exports.describeModelForRouter = exports.describeModel =
|
|
17
|
+
exports.McpOAuthClient = exports.McpOAuthAuthorization = exports.getAllMCPTools = exports.generateToolsForEntry = exports.generateAllTools = exports.toPublicMcpServiceToken = exports.resolveMcpServiceTokensOption = exports.MCP_SERVICE_TOKENS_SYNC_COLLECTION = exports.MCP_SERVICE_TOKENS_ROUTE_PATH = exports.MAX_ACTIVE_MCP_SERVICE_TOKENS = exports.createMcpServiceTokenRouter = exports.addMcpServiceTokenRoutes = exports.mountMCPServer = exports.generateToolDescription = exports.generateInputSchema = exports.updateMCPRegistryOptions = exports.registerMCPTool = exports.registerMCPModel = exports.getMCPRegistry = exports.clearMCPRegistry = exports.sendMcpOAuthChallenge = exports.resolveMcpOAuthOption = exports.buildProtectedResourceMetadata = exports.buildAuthorizationServerMetadata = exports.addMcpOAuthRoutes = exports.extractUserFromHeaders = exports.extractAuthFromHeaders = exports.resolveMcpRequestLogOption = exports.publicFrameworkModelName = exports.FRAMEWORK_MODEL_PUBLIC_NAMES = exports.getConsentStatuses = exports.resetAuditRecorderForTests = exports.recordAuditEvent = exports.persistEnqueuedAuditEvent = exports.maybeRecordAdminAudit = exports.isAuditRecorderInstalled = exports.flushAuditRecorderForTests = exports.persistRbacAuditToAuditEvent = exports.createCloudTasksAuditEnqueue = exports.auditEnqueueFromEnv = exports.AUDIT_SECRET_HEADER = exports.createAuditEventModel = exports.AUDIT_EVENT_SOURCES = exports.AuditApp = exports.recordSelfSecurityAction = exports.createSecurityEventsPlugin = exports.mountOrgSecurityRoutes = exports.createOrgSecurityAuthorizer = exports.suspendMembershipAction = exports.ISSUE_SIGN_IN_LINK_PERMISSION = void 0;
|
|
18
|
+
exports.getSocketUser = exports.createSocketAuthMiddleware = exports.createLegacyJwtValidator = exports.createBetterAuthValidator = exports.startSessionRevalidationSweep = exports.runSessionRevalidationSweep = exports.revalidateSocketSession = exports.reresolveSyncRoomsForSocket = exports.loadFullUserForSocket = exports.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS = exports.RealtimeApp = exports.installRealtimeSocketHandlers = exports.matchesQuery = exports.stopChangeStreamWatcher = exports.startChangeStreamWatcher = exports.emitSyncDeltaForChange = exports.emitPayloadToAuthorizedRoom = exports.USER_UPDATE_IDENTITY_ACTION = exports.USER_IDENTITY_FIELDS = exports.isWriteKeyForField = exports.isRbacUserModelName = exports.assertCanWriteUserIdentity = exports.assertCanWriteTargetUser = exports.rbacRouter = exports.terrenoDefaultRoles = exports.READ_ONLY_ROLE_PERMISSIONS = exports.organizationOperatorRole = exports.expandRolePermissions = exports.createRbacRoleModel = exports.ORG_ADMIN_PERMISSION_BUNDLE = exports.membershipOrgAdminPermissionSource = exports.MEMBERSHIP_ORG_ADMIN_PERMISSION_SOURCE_NAME = exports.backfillAdmins = exports.recordRbacAudit = exports.createRbacAuditModel = exports.assertAllowed = exports.DEFAULT_WINDOW_MS = exports.DEFAULT_AUTH_MAX = exports.DEFAULT_API_MAX = exports.createRouteRateLimitMiddleware = exports.notificationsBeforeSend = exports.NotificationsApp = exports.getNotificationService = exports.createNotificationService = exports.configureNotificationService = exports.McpToolSetting = exports.McpRequestLog = exports.McpOAuthToken = exports.McpOAuthFamilyRevokedError = exports.McpOAuthRevokedFamily = void 0;
|
|
19
|
+
exports.z = exports.WebhooksApp = exports.twilioSignature = exports.stripeSignature = exports.sendgridEventSignature = exports.hmacSignature = exports.createMemoryIdempotencyStore = exports.stripAdminBodyFields = exports.scrubAdminFields = exports.adminBodyFieldsToStrip = exports.SYSTEM_FIELD_PATHS = exports.nestDottedFieldDescriptions = exports.modelDescriptionToOpenApiSpec = exports.modelDescriptionToAdminFields = exports.fieldDescriptionToZodType = exports.fieldDescriptionToOpenApiProperty = exports.fieldDescriptionToAdminMeta = exports.describeModelForRouter = exports.describeModel = void 0;
|
|
20
20
|
var accessActions_1 = require("./accountSecurity/accessActions");
|
|
21
21
|
Object.defineProperty(exports, "ISSUE_SIGN_IN_LINK_PERMISSION", { enumerable: true, get: function () { return accessActions_1.ISSUE_SIGN_IN_LINK_PERMISSION; } });
|
|
22
22
|
__exportStar(require("./accountSecurity/accountSecurityApp"), exports);
|
|
@@ -102,13 +102,18 @@ var server_1 = require("./mcp/server");
|
|
|
102
102
|
Object.defineProperty(exports, "mountMCPServer", { enumerable: true, get: function () { return server_1.mountMCPServer; } });
|
|
103
103
|
var serviceTokens_1 = require("./mcp/serviceTokens");
|
|
104
104
|
Object.defineProperty(exports, "addMcpServiceTokenRoutes", { enumerable: true, get: function () { return serviceTokens_1.addMcpServiceTokenRoutes; } });
|
|
105
|
+
Object.defineProperty(exports, "createMcpServiceTokenRouter", { enumerable: true, get: function () { return serviceTokens_1.createMcpServiceTokenRouter; } });
|
|
105
106
|
Object.defineProperty(exports, "MAX_ACTIVE_MCP_SERVICE_TOKENS", { enumerable: true, get: function () { return serviceTokens_1.MAX_ACTIVE_MCP_SERVICE_TOKENS; } });
|
|
107
|
+
Object.defineProperty(exports, "MCP_SERVICE_TOKENS_ROUTE_PATH", { enumerable: true, get: function () { return serviceTokens_1.MCP_SERVICE_TOKENS_ROUTE_PATH; } });
|
|
108
|
+
Object.defineProperty(exports, "MCP_SERVICE_TOKENS_SYNC_COLLECTION", { enumerable: true, get: function () { return serviceTokens_1.MCP_SERVICE_TOKENS_SYNC_COLLECTION; } });
|
|
106
109
|
Object.defineProperty(exports, "resolveMcpServiceTokensOption", { enumerable: true, get: function () { return serviceTokens_1.resolveMcpServiceTokensOption; } });
|
|
110
|
+
Object.defineProperty(exports, "toPublicMcpServiceToken", { enumerable: true, get: function () { return serviceTokens_1.toPublicMcpServiceToken; } });
|
|
107
111
|
var toolGenerator_1 = require("./mcp/toolGenerator");
|
|
108
112
|
Object.defineProperty(exports, "generateAllTools", { enumerable: true, get: function () { return toolGenerator_1.generateAllTools; } });
|
|
109
113
|
Object.defineProperty(exports, "generateToolsForEntry", { enumerable: true, get: function () { return toolGenerator_1.generateToolsForEntry; } });
|
|
110
114
|
Object.defineProperty(exports, "getAllMCPTools", { enumerable: true, get: function () { return toolGenerator_1.getAllMCPTools; } });
|
|
111
115
|
__exportStar(require("./middleware"), exports);
|
|
116
|
+
__exportStar(require("./migrations/builtin/mcpServiceTokenStringIds"), exports);
|
|
112
117
|
__exportStar(require("./migrations/generate"), exports);
|
|
113
118
|
__exportStar(require("./migrations/load"), exports);
|
|
114
119
|
__exportStar(require("./migrations/lock"), exports);
|
|
@@ -206,26 +211,9 @@ Object.defineProperty(exports, "startChangeStreamWatcher", { enumerable: true, g
|
|
|
206
211
|
Object.defineProperty(exports, "stopChangeStreamWatcher", { enumerable: true, get: function () { return changeStreamWatcher_1.stopChangeStreamWatcher; } });
|
|
207
212
|
var queryMatcher_1 = require("./realtime/queryMatcher");
|
|
208
213
|
Object.defineProperty(exports, "matchesQuery", { enumerable: true, get: function () { return queryMatcher_1.matchesQuery; } });
|
|
209
|
-
var queryStore_1 = require("./realtime/queryStore");
|
|
210
|
-
Object.defineProperty(exports, "addQuerySubscription", { enumerable: true, get: function () { return queryStore_1.addQuerySubscription; } });
|
|
211
|
-
Object.defineProperty(exports, "clearQueryStore", { enumerable: true, get: function () { return queryStore_1.clearQueryStore; } });
|
|
212
|
-
Object.defineProperty(exports, "computeQueryId", { enumerable: true, get: function () { return queryStore_1.computeQueryId; } });
|
|
213
|
-
Object.defineProperty(exports, "getQuerySubscriptionsForCollection", { enumerable: true, get: function () { return queryStore_1.getQuerySubscriptionsForCollection; } });
|
|
214
|
-
Object.defineProperty(exports, "removeAllSocketQueries", { enumerable: true, get: function () { return queryStore_1.removeAllSocketQueries; } });
|
|
215
|
-
Object.defineProperty(exports, "removeQuerySubscription", { enumerable: true, get: function () { return queryStore_1.removeQuerySubscription; } });
|
|
216
214
|
var realtimeApp_1 = require("./realtime/realtimeApp");
|
|
217
215
|
Object.defineProperty(exports, "installRealtimeSocketHandlers", { enumerable: true, get: function () { return realtimeApp_1.installRealtimeSocketHandlers; } });
|
|
218
|
-
Object.defineProperty(exports, "MAX_DOCUMENT_SUBSCRIPTIONS", { enumerable: true, get: function () { return realtimeApp_1.MAX_DOCUMENT_SUBSCRIPTIONS; } });
|
|
219
|
-
Object.defineProperty(exports, "MAX_MODEL_SUBSCRIPTIONS", { enumerable: true, get: function () { return realtimeApp_1.MAX_MODEL_SUBSCRIPTIONS; } });
|
|
220
|
-
Object.defineProperty(exports, "MAX_QUERY_SUBSCRIPTIONS", { enumerable: true, get: function () { return realtimeApp_1.MAX_QUERY_SUBSCRIPTIONS; } });
|
|
221
216
|
Object.defineProperty(exports, "RealtimeApp", { enumerable: true, get: function () { return realtimeApp_1.RealtimeApp; } });
|
|
222
|
-
var registry_2 = require("./realtime/registry");
|
|
223
|
-
Object.defineProperty(exports, "clearRealtimeRegistry", { enumerable: true, get: function () { return registry_2.clearRealtimeRegistry; } });
|
|
224
|
-
Object.defineProperty(exports, "findRegistryEntryByCollection", { enumerable: true, get: function () { return registry_2.findRegistryEntryByCollection; } });
|
|
225
|
-
Object.defineProperty(exports, "findRegistryEntryByRoutePath", { enumerable: true, get: function () { return registry_2.findRegistryEntryByRoutePath; } });
|
|
226
|
-
Object.defineProperty(exports, "getRealtimeRegistry", { enumerable: true, get: function () { return registry_2.getRealtimeRegistry; } });
|
|
227
|
-
Object.defineProperty(exports, "registerRealtime", { enumerable: true, get: function () { return registry_2.registerRealtime; } });
|
|
228
|
-
Object.defineProperty(exports, "updateRealtimeRegistryOptions", { enumerable: true, get: function () { return registry_2.updateRealtimeRegistryOptions; } });
|
|
229
217
|
var sessionRevalidation_1 = require("./realtime/sessionRevalidation");
|
|
230
218
|
Object.defineProperty(exports, "DEFAULT_SESSION_REVALIDATION_INTERVAL_MS", { enumerable: true, get: function () { return sessionRevalidation_1.DEFAULT_SESSION_REVALIDATION_INTERVAL_MS; } });
|
|
231
219
|
Object.defineProperty(exports, "loadFullUserForSocket", { enumerable: true, get: function () { return sessionRevalidation_1.loadFullUserForSocket; } });
|
|
@@ -51,7 +51,7 @@ const recordMcpToolCall = (record, options) => {
|
|
|
51
51
|
oauthClientId: auth?.oauthClientId,
|
|
52
52
|
oauthFamilyId: auth?.oauthFamilyId,
|
|
53
53
|
outcome: record.outcome,
|
|
54
|
-
serviceTokenId:
|
|
54
|
+
serviceTokenId: auth?.serviceTokenId,
|
|
55
55
|
toolName: record.toolName,
|
|
56
56
|
userId: toObjectId(auth?.user?.id ? String(auth.user.id) : undefined),
|
|
57
57
|
}).catch((error) => {
|
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { Application } from "express";
|
|
2
|
-
import { type OpenApiMiddleware } from "../api";
|
|
2
|
+
import { type ModelRouterRegistration, type OpenApiMiddleware } from "../api";
|
|
3
3
|
export declare const MAX_ACTIVE_MCP_SERVICE_TOKENS = 10;
|
|
4
|
+
/** Route path of the self-serve MCP service token router. */
|
|
5
|
+
export declare const MCP_SERVICE_TOKENS_ROUTE_PATH = "/mcp/service-tokens";
|
|
6
|
+
/** Sync collection tag clients subscribe to (`mcp/service-tokens|owner:{userId}`). */
|
|
7
|
+
export declare const MCP_SERVICE_TOKENS_SYNC_COLLECTION = "mcp/service-tokens";
|
|
4
8
|
export interface McpServiceTokenRoutesOptions {
|
|
5
9
|
openApi?: OpenApiMiddleware;
|
|
6
10
|
publicMcpUrl?: string;
|
|
@@ -13,4 +17,20 @@ export declare const resolveMcpServiceTokensOption: (option: McpServiceTokensApp
|
|
|
13
17
|
enabled: boolean;
|
|
14
18
|
publicMcpUrl?: string;
|
|
15
19
|
};
|
|
20
|
+
/**
|
|
21
|
+
* Public shape of a stored MCP service token: every field except `tokenHash`, plus `id`.
|
|
22
|
+
* Used for REST responses, sync snapshots, and sync deltas so the hash never leaves the server.
|
|
23
|
+
*/
|
|
24
|
+
export declare const toPublicMcpServiceToken: (doc: Record<string, unknown>) => Record<string, unknown>;
|
|
25
|
+
/**
|
|
26
|
+
* Build the self-serve `/mcp/service-tokens` router. The collection is synced read-only
|
|
27
|
+
* (owner scope on `userId`): list/read over REST and sync, no client create/update/delete.
|
|
28
|
+
* Minting and revoking are the `create` collection action and `revoke` instance action.
|
|
29
|
+
*/
|
|
30
|
+
export declare const createMcpServiceTokenRouter: (options?: McpServiceTokenRoutesOptions) => ModelRouterRegistration;
|
|
31
|
+
/**
|
|
32
|
+
* Mount the self-serve MCP service token routes at `/mcp/service-tokens`. Callers must
|
|
33
|
+
* authenticate with a session or JWT; an `mcp_` bearer is rejected so a service token
|
|
34
|
+
* cannot list, mint, or revoke tokens.
|
|
35
|
+
*/
|
|
16
36
|
export declare const addMcpServiceTokenRoutes: (app: Application, options?: McpServiceTokenRoutesOptions) => void;
|
|
@@ -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
|
+
};
|
|
@@ -49,7 +49,7 @@ const mcpRequestLogSchema = new mongoose_1.default.Schema({
|
|
|
49
49
|
description: "Service token used for the call, when the credential was a service token",
|
|
50
50
|
index: true,
|
|
51
51
|
ref: "TerrenoMcpServiceToken",
|
|
52
|
-
type:
|
|
52
|
+
type: String,
|
|
53
53
|
},
|
|
54
54
|
toolName: {
|
|
55
55
|
description: "Name of the MCP tool that was called",
|