@terreno/api 57.20.0 → 57.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/biome.jsonc +3 -2
  3. package/dist/api.d.ts +3 -3
  4. package/dist/frameworkModelNames.d.ts +4 -0
  5. package/dist/frameworkModelNames.js +4 -0
  6. package/dist/index.d.ts +4 -0
  7. package/dist/index.js +9 -3
  8. package/dist/mcp/adminTracking.d.ts +28 -0
  9. package/dist/mcp/adminTracking.js +80 -0
  10. package/dist/mcp/auth.d.ts +6 -0
  11. package/dist/mcp/auth.js +12 -2
  12. package/dist/mcp/server.d.ts +8 -0
  13. package/dist/mcp/server.js +48 -4
  14. package/dist/models/mcpOAuthToken.js +27 -0
  15. package/dist/models/mcpRequestLog.d.ts +2 -0
  16. package/dist/models/mcpRequestLog.js +73 -0
  17. package/dist/models/mcpServiceToken.js +4 -0
  18. package/dist/models/mcpToolSetting.d.ts +2 -0
  19. package/dist/models/mcpToolSetting.js +119 -0
  20. package/dist/models/versionConfig.d.ts +2 -0
  21. package/dist/rbac/auditModel.d.ts +2 -1
  22. package/dist/terrenoApp.d.ts +12 -0
  23. package/dist/terrenoApp.js +3 -0
  24. package/dist/tests/models.d.ts +17 -22
  25. package/dist/tests/models.js +7 -1
  26. package/dist/tests/testHelper.d.ts +6 -12
  27. package/dist/tests.d.ts +1 -0
  28. package/dist/tests.js +3 -1
  29. package/dist/types/mcpAdmin.d.ts +58 -0
  30. package/dist/types/mcpAdmin.js +2 -0
  31. package/dist/types/mcpOAuth.d.ts +2 -0
  32. package/dist/types/mcpServiceToken.d.ts +2 -0
  33. package/e2e/smoke.ts +193 -0
  34. package/package.json +7 -5
  35. package/src/adminModelRouter.test.ts +8 -6
  36. package/src/api.arrayOperations.test.ts +31 -22
  37. package/src/api.hooks.test.ts +12 -11
  38. package/src/api.query.test.ts +2 -2
  39. package/src/api.test.ts +8 -7
  40. package/src/api.ts +3 -3
  41. package/src/audit/auditApp.test.ts +1 -1
  42. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  43. package/src/auth.test.ts +21 -7
  44. package/src/authRecovery.test.ts +10 -10
  45. package/src/authVerification.test.ts +7 -7
  46. package/src/betterAuthFeatures.test.ts +3 -2
  47. package/src/betterAuthLinking.test.ts +3 -1
  48. package/src/betterAuthSetup.test.ts +77 -51
  49. package/src/collectionRegistry.test.ts +4 -4
  50. package/src/frameworkModelNames.test.ts +8 -0
  51. package/src/frameworkModelNames.ts +4 -0
  52. package/src/githubAuth.test.ts +11 -11
  53. package/src/index.ts +8 -0
  54. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  55. package/src/mcp/actionTools.test.ts +11 -5
  56. package/src/mcp/adminTracking.test.ts +272 -0
  57. package/src/mcp/adminTracking.ts +104 -0
  58. package/src/mcp/auth.ts +18 -2
  59. package/src/mcp/oauth.test.ts +1 -1
  60. package/src/mcp/server.ts +67 -4
  61. package/src/mcp/serviceTokens.test.ts +2 -1
  62. package/src/mcp/toolGenerator.test.ts +9 -5
  63. package/src/migrations/cli.test.ts +15 -14
  64. package/src/migrations/cli.ts +1 -1
  65. package/src/migrations/generate.test.ts +2 -2
  66. package/src/migrations/load.test.ts +1 -1
  67. package/src/migrations/lock.test.ts +8 -3
  68. package/src/migrations/runner.test.ts +16 -5
  69. package/src/migrations/schemaCatalog.test.ts +4 -1
  70. package/src/models/mcpOAuthToken.test.ts +42 -0
  71. package/src/models/mcpOAuthToken.ts +32 -0
  72. package/src/models/mcpRequestLog.ts +81 -0
  73. package/src/models/mcpServiceToken.test.ts +23 -0
  74. package/src/models/mcpServiceToken.ts +10 -0
  75. package/src/models/mcpToolSetting.test.ts +69 -0
  76. package/src/models/mcpToolSetting.ts +138 -0
  77. package/src/models/versionConfig.ts +2 -0
  78. package/src/notifications/notificationsApp.test.ts +5 -8
  79. package/src/notifiers/slackWebApi.test.ts +30 -8
  80. package/src/openApi.test.ts +4 -4
  81. package/src/openApiValidator.test.ts +3 -3
  82. package/src/orgs/orgPermissions.test.ts +2 -2
  83. package/src/orgs/orgPlugin.test.ts +4 -3
  84. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  85. package/src/orgs/organizationSettings.test.ts +1 -1
  86. package/src/orgs/orgsApp.test.ts +5 -3
  87. package/src/permissions.test.ts +2 -2
  88. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  89. package/src/rbac/assertAllowed.test.ts +1 -1
  90. package/src/rbac/auditModel.ts +10 -2
  91. package/src/rbac/realtimeAccess.test.ts +3 -2
  92. package/src/rbac/routes.test.ts +1 -1
  93. package/src/rbac/userWriteGuards.test.ts +8 -5
  94. package/src/realtime/realtime.test.ts +35 -31
  95. package/src/scrubAdminFields.test.ts +1 -1
  96. package/src/sync/adminWindowMutation.test.ts +4 -3
  97. package/src/sync/executors.test.ts +1 -1
  98. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  99. package/src/sync/sync.test.ts +1 -1
  100. package/src/sync/syncPhaseC.test.ts +14 -11
  101. package/src/sync/syncRoutes.test.ts +8 -8
  102. package/src/sync/syncSeqPlugin.test.ts +1 -2
  103. package/src/sync/syncSocket.test.ts +5 -4
  104. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  105. package/src/terrenoApp.migrations.test.ts +8 -7
  106. package/src/terrenoApp.ts +14 -0
  107. package/src/tests/betterAuthStubs.ts +3 -2
  108. package/src/tests/bunSetup.ts +1 -1
  109. package/src/tests/models.ts +10 -0
  110. package/src/tests/testEnv.ts +7 -0
  111. package/src/tests.ts +1 -0
  112. package/src/types/mcpAdmin.ts +80 -0
  113. package/src/types/mcpOAuth.ts +5 -0
  114. package/src/types/mcpServiceToken.ts +5 -0
  115. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  116. package/tsconfig.typecheck.json +14 -0
@@ -8,11 +8,12 @@ import {join} from "node:path";
8
8
  import mongoose from "mongoose";
9
9
 
10
10
  import {setupDb} from "../tests";
11
+ import {partialEnv} from "../tests/testEnv";
11
12
  import {runMigrateCli} from "./cli";
12
- import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION} from "./types";
13
+ import {MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION, type MigrationStoreDoc} from "./types";
13
14
 
14
15
  const fixtures = (...parts: string[]): string => {
15
- return join(import.meta.dir, "fixtures", ...parts);
16
+ return join(__dirname, "fixtures", ...parts);
16
17
  };
17
18
 
18
19
  const capture = (): {
@@ -41,7 +42,7 @@ const capture = (): {
41
42
 
42
43
  const appliedIds = async (): Promise<string[]> => {
43
44
  const docs = await mongoose.connection
44
- .collection(MIGRATIONS_COLLECTION)
45
+ .collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION)
45
46
  .find({_id: {$ne: MIGRATION_LOCK_ID}})
46
47
  .project({id: 1})
47
48
  .toArray();
@@ -91,7 +92,7 @@ describe("runMigrateCli", () => {
91
92
  const io = capture();
92
93
  const code = await runMigrateCli({
93
94
  argv: ["status", "--dir", fixtures("valid")],
94
- env: {},
95
+ env: partialEnv({}),
95
96
  stderr: {write: io.writeErr},
96
97
  stdout: {write: io.writeOut},
97
98
  });
@@ -175,7 +176,7 @@ describe("runMigrateCli", () => {
175
176
  const modelsDir = await mkdtemp(join(tmpdir(), "migrate-cli-models-"));
176
177
  try {
177
178
  const modelsPath = join(modelsDir, "models.ts");
178
- const mongooseUrl = import.meta.resolve("mongoose");
179
+ const mongooseUrl = require.resolve("mongoose");
179
180
  await writeFile(
180
181
  modelsPath,
181
182
  `import mongoose from ${JSON.stringify(mongooseUrl)};
@@ -249,7 +250,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
249
250
  const io = capture();
250
251
  const code = await runMigrateCli({
251
252
  argv: ["up", "--dir", fixtures("valid"), "--force"],
252
- env: {NODE_ENV: "production"},
253
+ env: partialEnv({NODE_ENV: "production"}),
253
254
  mongoose,
254
255
  stderr: {write: io.writeErr},
255
256
  stdout: {write: io.writeOut},
@@ -263,7 +264,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
263
264
  const io = capture();
264
265
  const code = await runMigrateCli({
265
266
  argv: ["up", "--dir", fixtures("valid")],
266
- env: {ALLOW_MIGRATIONS: "true", NODE_ENV: "production"},
267
+ env: partialEnv({ALLOW_MIGRATIONS: "true", NODE_ENV: "production"}),
267
268
  mongoose,
268
269
  stderr: {write: io.writeErr},
269
270
  stdout: {write: io.writeOut},
@@ -276,7 +277,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
276
277
  const io = capture();
277
278
  const code = await runMigrateCli({
278
279
  argv: ["status", "--dir", fixtures("valid")],
279
- env: {NODE_ENV: "test"},
280
+ env: partialEnv({NODE_ENV: "test"}),
280
281
  mongoose,
281
282
  stderr: {write: io.writeErr},
282
283
  stdout: {write: io.writeOut},
@@ -290,7 +291,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
290
291
  const upIo = capture();
291
292
  const upCode = await runMigrateCli({
292
293
  argv: ["up", "--dir", fixtures("valid")],
293
- env: {NODE_ENV: "test"},
294
+ env: partialEnv({NODE_ENV: "test"}),
294
295
  mongoose,
295
296
  stderr: {write: upIo.writeErr},
296
297
  stdout: {write: upIo.writeOut},
@@ -301,7 +302,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
301
302
  const downIo = capture();
302
303
  const downCode = await runMigrateCli({
303
304
  argv: ["down", "--dir", fixtures("valid"), "--steps", "1"],
304
- env: {NODE_ENV: "test"},
305
+ env: partialEnv({NODE_ENV: "test"}),
305
306
  mongoose,
306
307
  stderr: {write: downIo.writeErr},
307
308
  stdout: {write: downIo.writeOut},
@@ -312,7 +313,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
312
313
  const statusIo = capture();
313
314
  const statusCode = await runMigrateCli({
314
315
  argv: ["status", "--dir", fixtures("valid")],
315
- env: {NODE_ENV: "test"},
316
+ env: partialEnv({NODE_ENV: "test"}),
316
317
  mongoose,
317
318
  stderr: {write: statusIo.writeErr},
318
319
  stdout: {write: statusIo.writeOut},
@@ -325,14 +326,14 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
325
326
  it("fails down when the target file has no down", async () => {
326
327
  await runMigrateCli({
327
328
  argv: ["up", "--dir", fixtures("valid")],
328
- env: {NODE_ENV: "test"},
329
+ env: partialEnv({NODE_ENV: "test"}),
329
330
  mongoose,
330
331
  stderr: {write: () => undefined},
331
332
  stdout: {write: () => undefined},
332
333
  });
333
334
  await runMigrateCli({
334
335
  argv: ["down", "--dir", fixtures("valid"), "--steps", "1"],
335
- env: {NODE_ENV: "test"},
336
+ env: partialEnv({NODE_ENV: "test"}),
336
337
  mongoose,
337
338
  stderr: {write: () => undefined},
338
339
  stdout: {write: () => undefined},
@@ -341,7 +342,7 @@ export const CliGenTodo = mongoose.models.CliGenTodo ?? mongoose.model("CliGenTo
341
342
  const io = capture();
342
343
  const code = await runMigrateCli({
343
344
  argv: ["down", "--dir", fixtures("valid"), "--steps", "1"],
344
- env: {NODE_ENV: "test"},
345
+ env: partialEnv({NODE_ENV: "test"}),
345
346
  mongoose,
346
347
  stderr: {write: io.writeErr},
347
348
  stdout: {write: io.writeOut},
@@ -276,7 +276,7 @@ export const runMigrateCli = async ({
276
276
  }
277
277
  };
278
278
 
279
- if (import.meta.main) {
279
+ if (Bun.main === __filename) {
280
280
  void runMigrateCli({argv: process.argv.slice(2)}).then((code) => {
281
281
  process.exit(code);
282
282
  });
@@ -12,14 +12,14 @@ import {generateMigration, lastSchemaAfter} from "./generate";
12
12
  import {checkMigrationFiles} from "./load";
13
13
 
14
14
  const fixtures = (...parts: string[]): string => {
15
- return join(import.meta.dir, "fixtures", ...parts);
15
+ return join(__dirname, "fixtures", ...parts);
16
16
  };
17
17
 
18
18
  const register = (name: string, schema: mongoose.Schema): mongoose.Model<mongoose.Document> => {
19
19
  if (mongoose.models[name]) {
20
20
  mongoose.deleteModel(name);
21
21
  }
22
- return mongoose.model(name, schema);
22
+ return mongoose.model<mongoose.Document>(name, schema);
23
23
  };
24
24
 
25
25
  const makeModels = ({
@@ -10,7 +10,7 @@ import {APIError} from "../errors";
10
10
  import {checkMigrationFiles, loadMigrations, resolveMigrationDir} from "./load";
11
11
 
12
12
  const fixtures = (...parts: string[]): string => {
13
- return join(import.meta.dir, "fixtures", ...parts);
13
+ return join(__dirname, "fixtures", ...parts);
14
14
  };
15
15
 
16
16
  describe("checkMigrationFiles", () => {
@@ -8,10 +8,15 @@ import mongoose from "mongoose";
8
8
  import {setupDb} from "../tests";
9
9
  import {withMigrationLock} from "./lock";
10
10
  import {runMigrations} from "./runner";
11
- import {type LoadedMigration, MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION} from "./types";
11
+ import {
12
+ type LoadedMigration,
13
+ MIGRATION_LOCK_ID,
14
+ MIGRATIONS_COLLECTION,
15
+ type MigrationStoreDoc,
16
+ } from "./types";
12
17
 
13
- const collection = (): mongoose.Collection => {
14
- return mongoose.connection.collection(MIGRATIONS_COLLECTION);
18
+ const collection = (): mongoose.Collection<MigrationStoreDoc> => {
19
+ return mongoose.connection.collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION);
15
20
  };
16
21
 
17
22
  describe("withMigrationLock", () => {
@@ -15,10 +15,21 @@ import {
15
15
  runDownMigrations,
16
16
  runMigrations,
17
17
  } from "./runner";
18
- import {type LoadedMigration, MIGRATION_LOCK_ID, MIGRATIONS_COLLECTION} from "./types";
18
+ import {
19
+ type LoadedMigration,
20
+ MIGRATION_LOCK_ID,
21
+ MIGRATIONS_COLLECTION,
22
+ type MigrationStoreDoc,
23
+ } from "./types";
24
+
25
+ /** Stored rows, including legacy ones that kept timestamps as ISO strings. */
26
+ type StoredMigrationDoc = Omit<MigrationStoreDoc, "appliedAt" | "expiresAt"> & {
27
+ appliedAt?: Date | string;
28
+ expiresAt?: Date | string;
29
+ };
19
30
 
20
- const collection = (): mongoose.Collection => {
21
- return mongoose.connection.collection(MIGRATIONS_COLLECTION);
31
+ const collection = (): mongoose.Collection<StoredMigrationDoc> => {
32
+ return mongoose.connection.collection<StoredMigrationDoc>(MIGRATIONS_COLLECTION);
22
33
  };
23
34
 
24
35
  const appliedIds = async (): Promise<string[]> => {
@@ -461,12 +472,12 @@ describe("assertMigrationsAllowed", () => {
461
472
 
462
473
  describe("exerciseReversibleMigrations", () => {
463
474
  const fixtures = (...parts: string[]): string => {
464
- return join(import.meta.dir, "fixtures", ...parts);
475
+ return join(__dirname, "fixtures", ...parts);
465
476
  };
466
477
 
467
478
  const sortedAppliedIds = async (): Promise<string[]> => {
468
479
  const docs = await mongoose.connection
469
- .collection(MIGRATIONS_COLLECTION)
480
+ .collection<MigrationStoreDoc>(MIGRATIONS_COLLECTION)
470
481
  .find({_id: {$ne: MIGRATION_LOCK_ID}})
471
482
  .project({id: 1})
472
483
  .toArray();
@@ -15,7 +15,10 @@ const catalogTodo = (): mongoose.Model<mongoose.Document> => {
15
15
  {collection: "todos"}
16
16
  );
17
17
  schema.index({title: 1});
18
- return mongoose.model(`TodoCatalog${Math.random().toString(16).slice(2)}`, schema);
18
+ return mongoose.model<mongoose.Document>(
19
+ `TodoCatalog${Math.random().toString(16).slice(2)}`,
20
+ schema
21
+ );
19
22
  };
20
23
 
21
24
  describe("buildSchemaCatalog", () => {
@@ -80,3 +80,45 @@ describe("McpOAuthToken family revocation", () => {
80
80
  expect(DateTime.fromJSDate(tombstone.expiresAt).diffNow("minutes").minutes).toBeGreaterThan(59);
81
81
  });
82
82
  });
83
+
84
+ describe("McpOAuthToken admin revocation", () => {
85
+ beforeEach(async () => {
86
+ await McpOAuthToken.deleteMany({});
87
+ await McpOAuthRevokedFamily.deleteMany({});
88
+ });
89
+
90
+ it("revokes the whole family and keeps the rows when a token row is deleted", async () => {
91
+ const first = await McpOAuthToken.issue(issueOptions());
92
+ const {familyId} = first.mcpOAuthToken;
93
+ await McpOAuthToken.issue({...issueOptions(familyId), userId: first.mcpOAuthToken.userId});
94
+
95
+ await McpOAuthToken.deleteOne({_id: first.mcpOAuthToken._id});
96
+
97
+ expect(await McpOAuthToken.countDocuments({familyId})).toBe(2);
98
+ expect(await activePairs(familyId)).toBe(0);
99
+ expect(await McpOAuthRevokedFamily.countDocuments({familyId})).toBe(1);
100
+ });
101
+
102
+ it("revokes the family through the document deleteOne method", async () => {
103
+ const {mcpOAuthToken} = await McpOAuthToken.issue(issueOptions());
104
+
105
+ await mcpOAuthToken.deleteOne();
106
+
107
+ expect(await McpOAuthToken.countDocuments({familyId: mcpOAuthToken.familyId})).toBe(1);
108
+ expect(await activePairs(mcpOAuthToken.familyId)).toBe(0);
109
+ });
110
+
111
+ it("revokes every family a user holds and leaves other users alone", async () => {
112
+ const userId = new mongoose.Types.ObjectId();
113
+ const a = await McpOAuthToken.issue({...issueOptions(), userId});
114
+ const b = await McpOAuthToken.issue({...issueOptions(), userId});
115
+ const other = await McpOAuthToken.issue(issueOptions());
116
+
117
+ const revoked = await McpOAuthToken.revokeAllForUser(userId);
118
+
119
+ expect(revoked).toBe(2);
120
+ expect(await activePairs(a.mcpOAuthToken.familyId)).toBe(0);
121
+ expect(await activePairs(b.mcpOAuthToken.familyId)).toBe(0);
122
+ expect(await activePairs(other.mcpOAuthToken.familyId)).toBe(1);
123
+ });
124
+ });
@@ -165,6 +165,20 @@ mcpOAuthTokenSchema.statics = {
165
165
  refreshToken: includeRefreshToken ? refreshSecret : undefined,
166
166
  };
167
167
  },
168
+ async revokeAllForUser(
169
+ this: McpOAuthTokenModel,
170
+ userId: mongoose.Types.ObjectId | string
171
+ ): Promise<number> {
172
+ const tokens = await this.find({
173
+ revokedAt: {$exists: false},
174
+ userId: new mongoose.Types.ObjectId(String(userId)),
175
+ }).select({familyId: 1});
176
+ const familyIds = new Set(tokens.map((token) => token.familyId));
177
+ for (const familyId of familyIds) {
178
+ await this.revokeFamily(familyId);
179
+ }
180
+ return familyIds.size;
181
+ },
168
182
  async revokeClient(this: McpOAuthTokenModel, clientId: string): Promise<void> {
169
183
  const tokens = await this.find({clientId, revokedAt: {$exists: false}}).select({familyId: 1});
170
184
  const familyIds = new Set(tokens.map((token) => token.familyId));
@@ -211,6 +225,24 @@ mcpOAuthTokenSchema.statics = {
211
225
  },
212
226
  };
213
227
 
228
+ // Deleting a token row (for example from the admin panel) revokes its whole rotation chain and
229
+ // keeps the rows, so the connection ends and its history stays visible.
230
+ mcpOAuthTokenSchema.methods = {
231
+ ...mcpOAuthTokenSchema.methods,
232
+ async deleteOne(this: McpOAuthTokenDocument): Promise<McpOAuthTokenDocument> {
233
+ await (this.constructor as McpOAuthTokenModel).revokeFamily(this.familyId);
234
+ return this;
235
+ },
236
+ };
237
+
238
+ mcpOAuthTokenSchema.pre("deleteOne", {document: false, query: true}, async function () {
239
+ const [existing] = await this.model.find(this.getFilter()).limit(1).select({familyId: 1});
240
+ if (existing) {
241
+ await (this.model as McpOAuthTokenModel).revokeFamily(existing.familyId);
242
+ }
243
+ this.setQuery({_id: {$exists: false}});
244
+ });
245
+
214
246
  export const McpOAuthToken =
215
247
  (mongoose.models.TerrenoMcpOAuthToken as McpOAuthTokenModel | undefined) ??
216
248
  mongoose.model<McpOAuthTokenDocument, McpOAuthTokenModel>(
@@ -0,0 +1,81 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
+ import type {McpRequestLogDocument, McpRequestLogModel} from "../types/mcpAdmin";
5
+
6
+ /**
7
+ * One row per MCP tool call when `mcpRequestLog` is on. Metadata only: tool arguments, results,
8
+ * and error messages are never stored. Rows expire at `expiresAt`.
9
+ */
10
+ const mcpRequestLogSchema = new mongoose.Schema<McpRequestLogDocument, McpRequestLogModel>(
11
+ {
12
+ credential: {
13
+ description: "Credential type that authenticated the call",
14
+ enum: ["jwt", "better-auth-session", "mcp-service-token", "oauth"],
15
+ type: String,
16
+ },
17
+ durationMs: {
18
+ description: "Time the tool handler took, in milliseconds",
19
+ required: true,
20
+ type: Number,
21
+ },
22
+ errorName: {
23
+ description: "Error class name when the tool threw; never the error message",
24
+ type: String,
25
+ },
26
+ expiresAt: {
27
+ description: "When this log row is removed",
28
+ required: true,
29
+ type: Date,
30
+ },
31
+ oauthClientId: {
32
+ description: "OAuth client id when the call used an MCP OAuth access token",
33
+ index: true,
34
+ type: String,
35
+ },
36
+ oauthFamilyId: {
37
+ description: "OAuth token family (one approved connection) when the call used OAuth",
38
+ type: String,
39
+ },
40
+ outcome: {
41
+ description: "ok, tool_error (the tool returned isError), or exception (the tool threw)",
42
+ enum: ["ok", "tool_error", "exception"],
43
+ required: true,
44
+ type: String,
45
+ },
46
+ serviceTokenId: {
47
+ description: "Service token used for the call, when the credential was a service token",
48
+ index: true,
49
+ ref: "TerrenoMcpServiceToken",
50
+ type: mongoose.Schema.Types.ObjectId,
51
+ },
52
+ toolName: {
53
+ description: "Name of the MCP tool that was called",
54
+ index: true,
55
+ required: true,
56
+ type: String,
57
+ },
58
+ userId: {
59
+ description: "User the call acted as",
60
+ index: true,
61
+ ref: "User",
62
+ type: mongoose.Schema.Types.ObjectId,
63
+ },
64
+ },
65
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
66
+ );
67
+
68
+ mcpRequestLogSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
69
+ mcpRequestLogSchema.index({created: -1});
70
+
71
+ mcpRequestLogSchema.plugin(createdUpdatedPlugin);
72
+ mcpRequestLogSchema.plugin(findOneOrNone);
73
+ mcpRequestLogSchema.plugin(findExactlyOne);
74
+
75
+ export const McpRequestLog =
76
+ (mongoose.models.TerrenoMcpRequestLog as McpRequestLogModel | undefined) ??
77
+ mongoose.model<McpRequestLogDocument, McpRequestLogModel>(
78
+ "TerrenoMcpRequestLog",
79
+ mcpRequestLogSchema,
80
+ "mcprequestlogs"
81
+ );
@@ -127,3 +127,26 @@ describe("McpServiceToken", () => {
127
127
  assert.isNull(await McpServiceToken.verify(issued.token));
128
128
  });
129
129
  });
130
+
131
+ describe("McpServiceToken.revokeAllForUser", () => {
132
+ beforeEach(async () => {
133
+ await McpServiceToken.deleteMany({});
134
+ });
135
+
136
+ it("revokes only that user's active tokens", async () => {
137
+ const userId = new mongoose.Types.ObjectId();
138
+ const otherId = new mongoose.Types.ObjectId();
139
+ await McpServiceToken.issueFor({_id: userId}, {name: "A"});
140
+ await McpServiceToken.issueFor({_id: userId}, {name: "B"});
141
+ await McpServiceToken.issueFor({_id: otherId}, {name: "Other"});
142
+
143
+ const revoked = await McpServiceToken.revokeAllForUser(userId);
144
+
145
+ assert.equal(revoked, 2);
146
+ assert.equal(await McpServiceToken.countDocuments({revokedAt: {$exists: false}, userId}), 0);
147
+ assert.equal(
148
+ await McpServiceToken.countDocuments({revokedAt: {$exists: false}, userId: otherId}),
149
+ 1
150
+ );
151
+ });
152
+ });
@@ -131,6 +131,16 @@ mcpServiceTokenSchema.statics = {
131
131
  });
132
132
  return {mcpServiceToken, token};
133
133
  },
134
+ async revokeAllForUser(
135
+ this: McpServiceTokenModel,
136
+ userId: mongoose.Types.ObjectId | string
137
+ ): Promise<number> {
138
+ const result = await this.updateMany(
139
+ {revokedAt: {$exists: false}, userId: new mongoose.Types.ObjectId(String(userId))},
140
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
141
+ );
142
+ return result.modifiedCount;
143
+ },
134
144
  async revokeForUser(
135
145
  this: McpServiceTokenModel,
136
146
  user: {_id: {toString(): string}},
@@ -0,0 +1,69 @@
1
+ import {afterEach, beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import {DateTime} from "luxon";
3
+
4
+ import {setupDb} from "../tests";
5
+ import {McpToolSetting} from "./mcpToolSetting";
6
+
7
+ describe("McpToolSetting.disabledNames", () => {
8
+ const restores: Array<() => void> = [];
9
+
10
+ beforeEach(async () => {
11
+ await setupDb();
12
+ await McpToolSetting.deleteMany({});
13
+ });
14
+
15
+ afterEach(() => {
16
+ for (const restore of restores.splice(0)) {
17
+ restore();
18
+ }
19
+ });
20
+
21
+ it("reuses the cached set until a write through the model clears it", async () => {
22
+ await McpToolSetting.create({enabled: false, name: "a", source: "custom"});
23
+ expect([...(await McpToolSetting.disabledNames())]).toEqual(["a"]);
24
+
25
+ // A write that bypasses the model's hooks is not seen until the cache expires.
26
+ await McpToolSetting.collection.updateOne({name: "a"}, {$set: {enabled: true}});
27
+ expect([...(await McpToolSetting.disabledNames())]).toEqual(["a"]);
28
+
29
+ await McpToolSetting.updateOne({name: "a"}, {$set: {enabled: false}});
30
+ await McpToolSetting.collection.updateOne({name: "a"}, {$set: {enabled: true}});
31
+ await McpToolSetting.updateOne({name: "b"}, {$set: {enabled: false}});
32
+ expect([...(await McpToolSetting.disabledNames())]).toEqual([]);
33
+ });
34
+
35
+ it("reads again after the TTL", async () => {
36
+ await McpToolSetting.create({enabled: false, name: "a", source: "custom"});
37
+ expect((await McpToolSetting.disabledNames()).size).toBe(1);
38
+ await McpToolSetting.collection.updateOne({name: "a"}, {$set: {enabled: true}});
39
+
40
+ const later = DateTime.now().plus({seconds: 10});
41
+ const now = spyOn(DateTime, "now").mockReturnValue(later);
42
+ restores.push(() => now.mockRestore());
43
+
44
+ expect((await McpToolSetting.disabledNames()).size).toBe(0);
45
+ });
46
+
47
+ it("keeps the last known switches when a read fails, and fails closed with none", async () => {
48
+ await McpToolSetting.create({enabled: false, name: "a", source: "custom"});
49
+ expect((await McpToolSetting.disabledNames()).size).toBe(1);
50
+
51
+ const later = DateTime.now().plus({seconds: 10});
52
+ const now = spyOn(DateTime, "now").mockReturnValue(later);
53
+ restores.push(() => now.mockRestore());
54
+ const find = spyOn(McpToolSetting, "find").mockImplementation(() => {
55
+ throw new Error("mongo down");
56
+ });
57
+ restores.push(() => find.mockRestore());
58
+
59
+ expect([...(await McpToolSetting.disabledNames())]).toEqual(["a"]);
60
+
61
+ find.mockRestore();
62
+ await McpToolSetting.deleteMany({});
63
+ const failing = spyOn(McpToolSetting, "find").mockImplementation(() => {
64
+ throw new Error("mongo down");
65
+ });
66
+ restores.push(() => failing.mockRestore());
67
+ await expect(McpToolSetting.disabledNames()).rejects.toThrow("mongo down");
68
+ });
69
+ });
@@ -0,0 +1,138 @@
1
+ import {DateTime} from "luxon";
2
+ import mongoose from "mongoose";
3
+
4
+ import {logger} from "../logger";
5
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
6
+ import type {McpToolSettingDocument, McpToolSettingModel, McpToolSource} from "../types/mcpAdmin";
7
+
8
+ /**
9
+ * Registry of MCP tools with an admin on/off switch. Rows are written when the server mounts
10
+ * with `mcpToolSettings` on. A tool with no row, or with `enabled: true`, is served.
11
+ */
12
+ const mcpToolSettingSchema = new mongoose.Schema<McpToolSettingDocument, McpToolSettingModel>(
13
+ {
14
+ description: {
15
+ description: "Tool description as sent to MCP clients",
16
+ type: String,
17
+ },
18
+ enabled: {
19
+ default: true,
20
+ description: "When false, the tool is hidden from tools/list and tools/call rejects it",
21
+ type: Boolean,
22
+ },
23
+ lastRegisteredAt: {
24
+ description: "Last server start that registered this tool",
25
+ type: Date,
26
+ },
27
+ name: {
28
+ description: "MCP tool name",
29
+ required: true,
30
+ type: String,
31
+ unique: true,
32
+ },
33
+ registered: {
34
+ default: true,
35
+ description: "False when the running server no longer registers this tool",
36
+ type: Boolean,
37
+ },
38
+ source: {
39
+ description: "model (generated from a modelRouter) or custom (registerMCPTool)",
40
+ enum: ["model", "custom"],
41
+ required: true,
42
+ type: String,
43
+ },
44
+ },
45
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
46
+ );
47
+
48
+ /** How long one process reuses the disabled-tool set before reading it again. */
49
+ const DISABLED_NAMES_TTL_MS = 5000;
50
+
51
+ // Per-process cache so /mcp does not query Mongo on every request. Writes through this model
52
+ // clear it at once; other processes pick up a change within DISABLED_NAMES_TTL_MS.
53
+ const disabledNamesCache: {expiresAt: number; names?: Set<string>} = {expiresAt: 0};
54
+
55
+ const clearDisabledNamesCache = (): void => {
56
+ disabledNamesCache.expiresAt = 0;
57
+ disabledNamesCache.names = undefined;
58
+ };
59
+
60
+ for (const hook of [
61
+ "save",
62
+ "updateOne",
63
+ "updateMany",
64
+ "findOneAndUpdate",
65
+ "deleteOne",
66
+ "deleteMany",
67
+ "findOneAndDelete",
68
+ ] as const) {
69
+ mcpToolSettingSchema.post(hook, clearDisabledNamesCache);
70
+ }
71
+ mcpToolSettingSchema.post("bulkWrite", clearDisabledNamesCache);
72
+
73
+ mcpToolSettingSchema.plugin(createdUpdatedPlugin);
74
+ mcpToolSettingSchema.plugin(findOneOrNone);
75
+ mcpToolSettingSchema.plugin(findExactlyOne);
76
+
77
+ mcpToolSettingSchema.statics = {
78
+ ...mcpToolSettingSchema.statics,
79
+ async disabledNames(this: McpToolSettingModel): Promise<Set<string>> {
80
+ const now = DateTime.now().toMillis();
81
+ if (disabledNamesCache.names && now < disabledNamesCache.expiresAt) {
82
+ return disabledNamesCache.names;
83
+ }
84
+ try {
85
+ const rows = await this.find({enabled: false}).select({name: 1}).lean();
86
+ const names = new Set(rows.map((row) => row.name));
87
+ disabledNamesCache.names = names;
88
+ disabledNamesCache.expiresAt = now + DISABLED_NAMES_TTL_MS;
89
+ return names;
90
+ } catch (error) {
91
+ // Keep enforcing the last known switches rather than re-enabling every tool. With no
92
+ // known state, fail the request (closed) instead of serving tools an admin turned off.
93
+ if (disabledNamesCache.names) {
94
+ logger.warn(`[mcp] Tool settings read failed; using last known: ${String(error)}`);
95
+ return disabledNamesCache.names;
96
+ }
97
+ throw error;
98
+ }
99
+ },
100
+ async syncRegistered(
101
+ this: McpToolSettingModel,
102
+ tools: Array<{description: string; name: string; source: McpToolSource}>
103
+ ): Promise<void> {
104
+ const now = DateTime.now().toJSDate();
105
+ if (tools.length > 0) {
106
+ // `enabled` is only set on insert so a restart never undoes an admin's switch.
107
+ await this.bulkWrite(
108
+ tools.map((tool) => ({
109
+ updateOne: {
110
+ filter: {name: tool.name},
111
+ update: {
112
+ $set: {
113
+ description: tool.description,
114
+ lastRegisteredAt: now,
115
+ registered: true,
116
+ source: tool.source,
117
+ },
118
+ $setOnInsert: {enabled: true},
119
+ },
120
+ upsert: true,
121
+ },
122
+ }))
123
+ );
124
+ }
125
+ await this.updateMany(
126
+ {name: {$nin: tools.map((tool) => tool.name)}, registered: {$ne: false}},
127
+ {$set: {registered: false}}
128
+ );
129
+ },
130
+ };
131
+
132
+ export const McpToolSetting =
133
+ (mongoose.models.TerrenoMcpToolSetting as McpToolSettingModel | undefined) ??
134
+ mongoose.model<McpToolSettingDocument, McpToolSettingModel>(
135
+ "TerrenoMcpToolSetting",
136
+ mcpToolSettingSchema,
137
+ "mcptoolsettings"
138
+ );
@@ -13,6 +13,8 @@ export interface VersionConfigDocument extends mongoose.Document {
13
13
  updateUrl?: string;
14
14
  /** How often clients should poll for version updates, in minutes. Defaults to 1440 (24 hours). */
15
15
  pollingIntervalMinutes: number;
16
+ /** Singleton sentinel backing the unique index; not selected by default. */
17
+ _singleton?: "config";
16
18
  created?: Date;
17
19
  updated?: Date;
18
20
  }