@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.
Files changed (183) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +1 -1
  3. package/biome.jsonc +3 -2
  4. package/dist/api.d.ts +3 -16
  5. package/dist/api.js +0 -9
  6. package/dist/auth.d.ts +3 -2
  7. package/dist/auth.js +95 -5
  8. package/dist/authRecovery.d.ts +2 -1
  9. package/dist/authRecovery.js +35 -17
  10. package/dist/collectionRegistry.d.ts +3 -4
  11. package/dist/collectionRegistry.js +0 -1
  12. package/dist/consentApp.d.ts +1 -1
  13. package/dist/consentApp.js +58 -2
  14. package/dist/frameworkModelNames.d.ts +4 -0
  15. package/dist/frameworkModelNames.js +4 -0
  16. package/dist/index.d.ts +8 -5
  17. package/dist/index.js +14 -20
  18. package/dist/mcp/adminTracking.d.ts +28 -0
  19. package/dist/mcp/adminTracking.js +80 -0
  20. package/dist/mcp/auth.d.ts +6 -0
  21. package/dist/mcp/auth.js +12 -2
  22. package/dist/mcp/server.d.ts +8 -0
  23. package/dist/mcp/server.js +48 -4
  24. package/dist/mcp/serviceTokens.d.ts +21 -1
  25. package/dist/mcp/serviceTokens.js +159 -183
  26. package/dist/migrations/builtin/mcpServiceTokenStringIds.d.ts +18 -0
  27. package/dist/migrations/builtin/mcpServiceTokenStringIds.js +67 -0
  28. package/dist/models/mcpOAuthToken.js +27 -0
  29. package/dist/models/mcpRequestLog.d.ts +2 -0
  30. package/dist/models/mcpRequestLog.js +73 -0
  31. package/dist/models/mcpServiceToken.js +40 -4
  32. package/dist/models/mcpToolSetting.d.ts +2 -0
  33. package/dist/models/mcpToolSetting.js +119 -0
  34. package/dist/models/versionConfig.d.ts +2 -0
  35. package/dist/openApiBuilder.d.ts +4 -0
  36. package/dist/openApiBuilder.js +2 -0
  37. package/dist/rbac/auditModel.d.ts +2 -1
  38. package/dist/rbac/realtimeAccess.d.ts +5 -4
  39. package/dist/rbac/realtimeAccess.js +17 -64
  40. package/dist/realtime/changeStreamWatcher.d.ts +8 -63
  41. package/dist/realtime/changeStreamWatcher.js +32 -391
  42. package/dist/realtime/realtimeApp.d.ts +14 -27
  43. package/dist/realtime/realtimeApp.js +14 -220
  44. package/dist/realtime/types.d.ts +0 -64
  45. package/dist/sync/executors.js +14 -2
  46. package/dist/sync/socketHandlers.d.ts +1 -1
  47. package/dist/sync/socketHandlers.js +1 -1
  48. package/dist/terrenoApp.d.ts +19 -5
  49. package/dist/terrenoApp.js +21 -14
  50. package/dist/tests/models.d.ts +17 -22
  51. package/dist/tests/models.js +7 -1
  52. package/dist/tests/openApiResponseSchema.d.ts +39 -0
  53. package/dist/tests/openApiResponseSchema.js +56 -0
  54. package/dist/tests/testHelper.d.ts +6 -12
  55. package/dist/tests.d.ts +2 -0
  56. package/dist/tests.js +6 -1
  57. package/dist/types/mcpAdmin.d.ts +58 -0
  58. package/dist/types/mcpAdmin.js +2 -0
  59. package/dist/types/mcpOAuth.d.ts +2 -0
  60. package/dist/types/mcpServiceToken.d.ts +9 -4
  61. package/dist/versionCheckPlugin.d.ts +1 -1
  62. package/dist/versionCheckPlugin.js +25 -2
  63. package/e2e/smoke.ts +193 -0
  64. package/package.json +14 -8
  65. package/src/__snapshots__/openApi.test.ts.snap +4986 -2478
  66. package/src/__snapshots__/openApiBuilder.test.ts.snap +836 -0
  67. package/src/__tests__/openApiResponseSchema.test.ts +148 -0
  68. package/src/__tests__/versionCheckPlugin.test.ts +72 -0
  69. package/src/adminModelRouter.test.ts +8 -6
  70. package/src/api.arrayOperations.test.ts +31 -22
  71. package/src/api.hooks.test.ts +12 -11
  72. package/src/api.query.test.ts +2 -2
  73. package/src/api.test.ts +17 -14
  74. package/src/api.ts +3 -27
  75. package/src/audit/auditApp.test.ts +1 -1
  76. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  77. package/src/auth.test.ts +21 -7
  78. package/src/auth.ts +116 -5
  79. package/src/authOpenApi.test.ts +316 -0
  80. package/src/authRecovery.test.ts +10 -10
  81. package/src/authRecovery.ts +47 -19
  82. package/src/authVerification.test.ts +7 -7
  83. package/src/betterAuthFeatures.test.ts +3 -2
  84. package/src/betterAuthLinking.test.ts +3 -1
  85. package/src/betterAuthOAuthHandoff.test.ts +13 -5
  86. package/src/betterAuthSetup.test.ts +77 -51
  87. package/src/collectionRegistry.test.ts +4 -4
  88. package/src/collectionRegistry.ts +3 -5
  89. package/src/consentApp.test.ts +98 -0
  90. package/src/consentApp.ts +67 -2
  91. package/src/frameworkModelNames.test.ts +8 -0
  92. package/src/frameworkModelNames.ts +4 -0
  93. package/src/githubAuth.test.ts +11 -11
  94. package/src/index.ts +14 -28
  95. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  96. package/src/mcp/actionTools.test.ts +13 -7
  97. package/src/mcp/adminTracking.test.ts +272 -0
  98. package/src/mcp/adminTracking.ts +104 -0
  99. package/src/mcp/auth.test.ts +7 -3
  100. package/src/mcp/auth.ts +18 -2
  101. package/src/mcp/oauth.test.ts +13 -13
  102. package/src/mcp/server.ts +67 -4
  103. package/src/mcp/serviceTokens.sync.test.ts +230 -0
  104. package/src/mcp/serviceTokens.test.ts +114 -62
  105. package/src/mcp/serviceTokens.ts +193 -212
  106. package/src/mcp/toolGenerator.test.ts +9 -5
  107. package/src/migrations/builtin/mcpServiceTokenStringIds.test.ts +194 -0
  108. package/src/migrations/builtin/mcpServiceTokenStringIds.ts +121 -0
  109. package/src/migrations/cli.test.ts +15 -14
  110. package/src/migrations/cli.ts +1 -1
  111. package/src/migrations/generate.test.ts +2 -2
  112. package/src/migrations/load.test.ts +1 -1
  113. package/src/migrations/lock.test.ts +8 -3
  114. package/src/migrations/runner.test.ts +16 -5
  115. package/src/migrations/schemaCatalog.test.ts +4 -1
  116. package/src/models/mcpOAuthToken.test.ts +42 -0
  117. package/src/models/mcpOAuthToken.ts +32 -0
  118. package/src/models/mcpRequestLog.ts +81 -0
  119. package/src/models/mcpServiceToken.test.ts +75 -5
  120. package/src/models/mcpServiceToken.ts +61 -14
  121. package/src/models/mcpToolSetting.test.ts +69 -0
  122. package/src/models/mcpToolSetting.ts +138 -0
  123. package/src/models/versionConfig.ts +2 -0
  124. package/src/notifications/notificationsApp.test.ts +5 -8
  125. package/src/notifiers/slackWebApi.test.ts +30 -8
  126. package/src/openApi.test.ts +4 -4
  127. package/src/openApiBuilder.test.ts +34 -1
  128. package/src/openApiBuilder.ts +5 -0
  129. package/src/openApiValidator.test.ts +3 -3
  130. package/src/orgs/orgPermissions.test.ts +2 -2
  131. package/src/orgs/orgPlugin.test.ts +4 -3
  132. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  133. package/src/orgs/organizationSettings.test.ts +1 -1
  134. package/src/orgs/orgsApp.test.ts +5 -3
  135. package/src/permissions.test.ts +2 -2
  136. package/src/rateLimit/rateLimit.test.ts +25 -10
  137. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  138. package/src/rbac/assertAllowed.test.ts +1 -1
  139. package/src/rbac/auditModel.ts +10 -2
  140. package/src/rbac/realtimeAccess.test.ts +20 -171
  141. package/src/rbac/realtimeAccess.ts +17 -82
  142. package/src/rbac/routes.test.ts +1 -1
  143. package/src/rbac/userWriteGuards.test.ts +8 -5
  144. package/src/realtime/changeStreamWatcher.ts +43 -506
  145. package/src/realtime/realtime.test.ts +211 -2547
  146. package/src/realtime/realtimeApp.ts +16 -295
  147. package/src/realtime/types.ts +0 -72
  148. package/src/scrubAdminFields.test.ts +1 -1
  149. package/src/sync/adminWindowMutation.test.ts +4 -3
  150. package/src/sync/executors.test.ts +29 -1
  151. package/src/sync/executors.ts +23 -2
  152. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  153. package/src/sync/socketHandlers.ts +1 -1
  154. package/src/sync/sync.test.ts +1 -1
  155. package/src/sync/syncPhaseC.test.ts +14 -11
  156. package/src/sync/syncRoutes.test.ts +8 -8
  157. package/src/sync/syncSeqPlugin.test.ts +1 -2
  158. package/src/sync/syncSocket.test.ts +78 -113
  159. package/src/terrenoApp.mcpServiceTokens.test.ts +16 -8
  160. package/src/terrenoApp.migrations.test.ts +8 -7
  161. package/src/terrenoApp.ts +38 -18
  162. package/src/tests/betterAuthStubs.ts +3 -2
  163. package/src/tests/bunSetup.ts +1 -1
  164. package/src/tests/models.ts +10 -0
  165. package/src/tests/openApiResponseSchema.ts +104 -0
  166. package/src/tests/testEnv.ts +7 -0
  167. package/src/tests.ts +8 -0
  168. package/src/types/mcpAdmin.ts +80 -0
  169. package/src/types/mcpOAuth.ts +5 -0
  170. package/src/types/mcpServiceToken.ts +12 -4
  171. package/src/versionCheckPlugin.ts +41 -2
  172. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  173. package/tsconfig.typecheck.json +14 -0
  174. package/dist/realtime/deprecation.d.ts +0 -13
  175. package/dist/realtime/deprecation.js +0 -31
  176. package/dist/realtime/queryStore.d.ts +0 -37
  177. package/dist/realtime/queryStore.js +0 -103
  178. package/dist/realtime/registry.d.ts +0 -15
  179. package/dist/realtime/registry.js +0 -52
  180. package/src/realtime/deprecation.test.ts +0 -60
  181. package/src/realtime/deprecation.ts +0 -33
  182. package/src/realtime/queryStore.ts +0 -122
  183. package/src/realtime/registry.ts +0 -84
@@ -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: String,
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
+ );
@@ -1,16 +1,20 @@
1
1
  import {beforeEach, describe, it} from "bun:test";
2
- import {createHash} from "node:crypto";
2
+ import {createHash, randomUUID} from "node:crypto";
3
3
  import {assert} from "chai";
4
4
  import {DateTime} from "luxon";
5
5
  import mongoose from "mongoose";
6
6
 
7
+ import {clearSyncRegistry} from "../sync/registry";
7
8
  import {McpServiceToken} from "./mcpServiceToken";
8
9
 
9
10
  const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
10
11
 
11
12
  describe("McpServiceToken", () => {
12
13
  beforeEach(async () => {
13
- await McpServiceToken.deleteMany({});
14
+ // Model-level behaviour without the /mcp/service-tokens sync registration.
15
+ clearSyncRegistry();
16
+ // Model.deleteMany is rejected once the collection is sync-registered by another suite.
17
+ await McpServiceToken.collection.deleteMany({});
14
18
  await McpServiceToken.syncIndexes();
15
19
  });
16
20
 
@@ -25,6 +29,51 @@ describe("McpServiceToken", () => {
25
29
  assert.notInclude(JSON.stringify(issued.mcpServiceToken.toJSON()), issued.token);
26
30
  });
27
31
 
32
+ it("mints UUID string ids", async () => {
33
+ const issued = await McpServiceToken.issueFor(
34
+ {_id: new mongoose.Types.ObjectId()},
35
+ {name: "Uuid"}
36
+ );
37
+
38
+ assert.isString(issued.mcpServiceToken._id);
39
+ assert.match(
40
+ issued.mcpServiceToken._id,
41
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
42
+ );
43
+ assert.isFalse(issued.mcpServiceToken.deleted);
44
+ });
45
+
46
+ it("turns a soft delete into a revoke so the row stays visible", async () => {
47
+ const issued = await McpServiceToken.issueFor(
48
+ {_id: new mongoose.Types.ObjectId()},
49
+ {name: "Soft delete"}
50
+ );
51
+
52
+ issued.mcpServiceToken.deleted = true;
53
+ await issued.mcpServiceToken.save();
54
+
55
+ const stored = await McpServiceToken.findExactlyOne({_id: issued.mcpServiceToken._id});
56
+ assert.isFalse(stored.deleted);
57
+ assert.instanceOf(stored.revokedAt, Date);
58
+ assert.isNull(await McpServiceToken.verify(issued.token));
59
+ });
60
+
61
+ it("keeps an existing revokedAt when a revoked token is soft deleted", async () => {
62
+ const issued = await McpServiceToken.issueFor(
63
+ {_id: new mongoose.Types.ObjectId()},
64
+ {name: "Already revoked"}
65
+ );
66
+ const revokedAt = DateTime.now().minus({day: 1}).toJSDate();
67
+ issued.mcpServiceToken.revokedAt = revokedAt;
68
+ await issued.mcpServiceToken.save();
69
+
70
+ issued.mcpServiceToken.deleted = true;
71
+ await issued.mcpServiceToken.save();
72
+
73
+ const stored = await McpServiceToken.findExactlyOne({_id: issued.mcpServiceToken._id});
74
+ assert.equal(stored.revokedAt?.getTime(), revokedAt.getTime());
75
+ });
76
+
28
77
  it("verifies an active token but not a revoked or expired token", async () => {
29
78
  const userId = new mongoose.Types.ObjectId();
30
79
  const active = await McpServiceToken.issueFor({_id: userId}, {name: "Active"});
@@ -63,9 +112,7 @@ describe("McpServiceToken", () => {
63
112
  assert.instanceOf(revoked?.revokedAt, Date);
64
113
 
65
114
  assert.isNull(await McpServiceToken.revokeForUser({_id: ownerId}, issued.mcpServiceToken._id));
66
- assert.isNull(
67
- await McpServiceToken.revokeForUser({_id: ownerId}, new mongoose.Types.ObjectId())
68
- );
115
+ assert.isNull(await McpServiceToken.revokeForUser({_id: ownerId}, randomUUID()));
69
116
  });
70
117
 
71
118
  it("enforces unique token hashes", async () => {
@@ -127,3 +174,26 @@ describe("McpServiceToken", () => {
127
174
  assert.isNull(await McpServiceToken.verify(issued.token));
128
175
  });
129
176
  });
177
+
178
+ describe("McpServiceToken.revokeAllForUser", () => {
179
+ beforeEach(async () => {
180
+ await McpServiceToken.deleteMany({});
181
+ });
182
+
183
+ it("revokes only that user's active tokens", async () => {
184
+ const userId = new mongoose.Types.ObjectId();
185
+ const otherId = new mongoose.Types.ObjectId();
186
+ await McpServiceToken.issueFor({_id: userId}, {name: "A"});
187
+ await McpServiceToken.issueFor({_id: userId}, {name: "B"});
188
+ await McpServiceToken.issueFor({_id: otherId}, {name: "Other"});
189
+
190
+ const revoked = await McpServiceToken.revokeAllForUser(userId);
191
+
192
+ assert.equal(revoked, 2);
193
+ assert.equal(await McpServiceToken.countDocuments({revokedAt: {$exists: false}, userId}), 0);
194
+ assert.equal(
195
+ await McpServiceToken.countDocuments({revokedAt: {$exists: false}, userId: otherId}),
196
+ 1
197
+ );
198
+ });
199
+ });
@@ -1,8 +1,15 @@
1
- import {createHash, randomBytes} from "node:crypto";
1
+ import {createHash, randomBytes, randomUUID} from "node:crypto";
2
2
  import {DateTime} from "luxon";
3
3
  import mongoose from "mongoose";
4
4
 
5
- import {createdUpdatedPlugin, findExactlyOne, findOneOrNone, findOneOrNoneFor} from "../plugins";
5
+ import {
6
+ createdUpdatedPlugin,
7
+ findExactlyOne,
8
+ findOneOrNone,
9
+ findOneOrNoneFor,
10
+ isDeletedPlugin,
11
+ } from "../plugins";
12
+ import {syncPlugin} from "../sync/syncSeqPlugin";
6
13
  import type {McpServiceTokenDocument, McpServiceTokenModel} from "../types/mcpServiceToken";
7
14
 
8
15
  export type {
@@ -20,6 +27,13 @@ const hashToken = (token: string): string => createHash("sha256").update(token).
20
27
 
21
28
  const mcpServiceTokenSchema = new mongoose.Schema<McpServiceTokenDocument, McpServiceTokenModel>(
22
29
  {
30
+ _id: {
31
+ // Synced collections use String ids. New rows get a UUID; rows created before
32
+ // Terreno 58 keep their ObjectId hex after the mcp-service-token-string-ids migration.
33
+ default: (): string => randomUUID(),
34
+ description: "The MCP service token id (String so the synced collection can address it)",
35
+ type: String,
36
+ },
23
37
  expiresAt: {
24
38
  description: "When this MCP service token expires; unset when it does not expire",
25
39
  type: Date,
@@ -69,9 +83,26 @@ mcpServiceTokenSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
69
83
  mcpServiceTokenSchema.index({revokedAt: 1, userId: 1});
70
84
 
71
85
  mcpServiceTokenSchema.plugin(createdUpdatedPlugin);
86
+ mcpServiceTokenSchema.plugin(isDeletedPlugin);
72
87
  mcpServiceTokenSchema.plugin(findOneOrNone);
73
88
  mcpServiceTokenSchema.plugin(findExactlyOne);
74
89
 
90
+ // Deleting a token means revoking it: the row stays visible to its owner (and the audit
91
+ // trail) with `revokedAt` set. A soft delete (admin DELETE through modelRouter sets
92
+ // `deleted: true`) is turned into a revoke so it never tombstones the owner's synced row.
93
+ mcpServiceTokenSchema.pre("save", function () {
94
+ if (!this.isModified("deleted") || this.deleted !== true) {
95
+ return;
96
+ }
97
+ this.deleted = false;
98
+ if (!this.revokedAt) {
99
+ this.revokedAt = DateTime.now().toJSDate();
100
+ }
101
+ });
102
+
103
+ // Stamps a per-stream _syncSeq on every write; required by the /mcp/service-tokens sync config.
104
+ mcpServiceTokenSchema.plugin(syncPlugin);
105
+
75
106
  const revokeInsteadOfDelete = async (
76
107
  doc: McpServiceTokenDocument | null
77
108
  ): Promise<McpServiceTokenDocument | null> => {
@@ -93,6 +124,9 @@ mcpServiceTokenSchema.methods = {
93
124
  },
94
125
  };
95
126
 
127
+ // Query deleteOne revokes instead of removing the row. Registered after syncPlugin so that,
128
+ // once the collection is synced, syncPlugin's hard-delete guard rejects the call before any
129
+ // write happens.
96
130
  mcpServiceTokenSchema.pre("deleteOne", {document: false, query: true}, async function () {
97
131
  const existing = await findOneOrNoneFor(this.model, this.getFilter());
98
132
  await revokeInsteadOfDelete(existing as McpServiceTokenDocument | null);
@@ -103,7 +137,7 @@ mcpServiceTokenSchema.statics = {
103
137
  ...mcpServiceTokenSchema.statics,
104
138
  async countActiveForUser(
105
139
  this: McpServiceTokenModel,
106
- userId: mongoose.Types.ObjectId
140
+ userId: mongoose.Types.ObjectId | string
107
141
  ): Promise<number> {
108
142
  const now = DateTime.now().toJSDate();
109
143
  return this.countDocuments({
@@ -131,14 +165,24 @@ mcpServiceTokenSchema.statics = {
131
165
  });
132
166
  return {mcpServiceToken, token};
133
167
  },
168
+ async revokeAllForUser(
169
+ this: McpServiceTokenModel,
170
+ userId: mongoose.Types.ObjectId | string
171
+ ): Promise<number> {
172
+ const result = await this.updateMany(
173
+ {revokedAt: {$exists: false}, userId: new mongoose.Types.ObjectId(String(userId))},
174
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
175
+ );
176
+ return result.modifiedCount;
177
+ },
134
178
  async revokeForUser(
135
179
  this: McpServiceTokenModel,
136
180
  user: {_id: {toString(): string}},
137
- tokenId: mongoose.Types.ObjectId
181
+ tokenId: string
138
182
  ): Promise<McpServiceTokenDocument | null> {
139
183
  return this.findOneAndUpdate(
140
184
  {
141
- _id: tokenId,
185
+ _id: String(tokenId),
142
186
  revokedAt: {$exists: false},
143
187
  userId: new mongoose.Types.ObjectId(String(user._id)),
144
188
  },
@@ -155,14 +199,17 @@ mcpServiceTokenSchema.statics = {
155
199
  user: {_id: {toString(): string}; tokenEpoch?: number}
156
200
  ): Promise<void> {
157
201
  const currentEpoch = user.tokenEpoch ?? 0;
158
- await this.updateMany(
159
- {
160
- revokedAt: {$exists: false},
161
- tokenEpoch: {$nin: currentEpoch === 0 ? [0, null] : [currentEpoch]},
162
- userId: new mongoose.Types.ObjectId(String(user._id)),
163
- },
164
- {$set: {revokedAt: DateTime.now().toJSDate()}}
165
- );
202
+ const userId = new mongoose.Types.ObjectId(String(user._id));
203
+ const outdated = await this.find({
204
+ revokedAt: {$exists: false},
205
+ tokenEpoch: {$nin: currentEpoch === 0 ? [0, null] : [currentEpoch]},
206
+ userId,
207
+ });
208
+ const revokedAt = DateTime.now().toJSDate();
209
+ for (const token of outdated) {
210
+ token.revokedAt = revokedAt;
211
+ await token.save();
212
+ }
166
213
  },
167
214
  async verify(this: McpServiceTokenModel, token: string): Promise<McpServiceTokenDocument | null> {
168
215
  const now = DateTime.now().toJSDate();
@@ -175,7 +222,7 @@ mcpServiceTokenSchema.statics = {
175
222
  };
176
223
 
177
224
  export const McpServiceToken =
178
- (mongoose.models.TerrenoMcpServiceToken as McpServiceTokenModel | undefined) ??
225
+ (mongoose.models.TerrenoMcpServiceToken as unknown as McpServiceTokenModel | undefined) ??
179
226
  mongoose.model<McpServiceTokenDocument, McpServiceTokenModel>(
180
227
  "TerrenoMcpServiceToken",
181
228
  mcpServiceTokenSchema,
@@ -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
  }
@@ -12,7 +12,7 @@ import {NotificationPreference} from "../models/notificationPreference";
12
12
  import {clearSyncRegistry} from "../sync/registry";
13
13
  import {SyncApp} from "../sync/syncApp";
14
14
  import {TerrenoApp} from "../terrenoApp";
15
- import {authAsUser, setupDb, UserModel} from "../tests";
15
+ import {authAsUser, authUserModel, setupDb, UserModel} from "../tests";
16
16
  import {configureNotificationService, getNotificationService} from "./notificationService";
17
17
  import {NotificationsApp} from "./notificationsApp";
18
18
  import {
@@ -23,7 +23,7 @@ import {
23
23
  interface FakeComms {
24
24
  mailCalls: Array<{html?: string; subject: string; to: string}>;
25
25
  mailUserIds: Array<string | undefined>;
26
- pushCalls: Array<{title: string; userId: string}>;
26
+ pushCalls: Array<{body: string; title: string; userId: string}>;
27
27
  smsCalls: Array<{body: string; to: string}>;
28
28
  smsUserIds: Array<string | undefined>;
29
29
  }
@@ -37,7 +37,7 @@ const buildFakeComms = (
37
37
  message: {html?: string; subject: string; to: string},
38
38
  options?: {userId?: string}
39
39
  ) => Promise<{accepted: boolean}>;
40
- sendPushToUser: (message: {title: string; userId: string}) => Promise<unknown[]>;
40
+ sendPushToUser: (message: {body: string; title: string; userId: string}) => Promise<unknown[]>;
41
41
  sendSms: (
42
42
  message: {body: string; to: string},
43
43
  options?: {userId?: string}
@@ -77,10 +77,7 @@ const buildFakeComms = (
77
77
  };
78
78
 
79
79
  const buildApp = (
80
- options: {
81
- getComms?: () => ReturnType<typeof buildFakeComms>["getComms"];
82
- retainDays?: number;
83
- } = {}
80
+ options: {getComms?: ReturnType<typeof buildFakeComms>["getComms"]; retainDays?: number} = {}
84
81
  ): express.Application => {
85
82
  clearSyncRegistry();
86
83
  return new TerrenoApp({
@@ -114,7 +111,7 @@ describe("NotificationsApp", () => {
114
111
  const app = buildApp();
115
112
  userAgent = await authAsUser(app, "notAdmin");
116
113
  await UserModel.deleteOne({email: "other-user@example.com"});
117
- await signupUser(UserModel, "other-user@example.com", "password");
114
+ await signupUser(authUserModel, "other-user@example.com", "password");
118
115
  otherUserAgent = await authWithCredentials(app, {
119
116
  email: "other-user@example.com",
120
117
  password: "password",
@@ -22,13 +22,35 @@ describe("normalizeSlackChannelName", () => {
22
22
  });
23
23
  });
24
24
 
25
+ /** The request body fields the Slack helpers send. */
26
+ interface SlackRequestBody {
27
+ blocks?: unknown[];
28
+ channel?: string;
29
+ force?: boolean;
30
+ name?: string;
31
+ text?: string;
32
+ users?: string;
33
+ }
34
+
35
+ /** Slack doubles return `data`, `status`, and sometimes `headers`, not a whole AxiosResponse. */
36
+ interface SlackResponseDouble {
37
+ data: unknown;
38
+ headers?: {get: (name: string) => string | undefined};
39
+ status: number;
40
+ }
41
+ type AxiosPostDouble = (url: string, body: SlackRequestBody) => Promise<SlackResponseDouble>;
42
+ type AxiosGetDouble = (
43
+ url: string,
44
+ config?: {params?: {types?: string}}
45
+ ) => Promise<SlackResponseDouble>;
46
+
25
47
  describe("Slack Web API", () => {
26
- let mockAxiosPost: Mock<typeof axios.post>;
27
- let mockAxiosGet: Mock<typeof axios.get>;
48
+ let mockAxiosPost: Mock<AxiosPostDouble>;
49
+ let mockAxiosGet: Mock<AxiosGetDouble>;
28
50
 
29
51
  beforeEach(() => {
30
- mockAxiosPost = spyOn(axios, "post");
31
- mockAxiosGet = spyOn(axios, "get");
52
+ mockAxiosPost = spyOn(axios, "post") as unknown as Mock<AxiosPostDouble>;
53
+ mockAxiosGet = spyOn(axios, "get") as unknown as Mock<AxiosGetDouble>;
32
54
  process.env.SLACK_BOT_TOKEN = "xoxb-test";
33
55
  (Sentry.captureException as Mock<typeof Sentry.captureException>).mockClear();
34
56
  });
@@ -40,7 +62,7 @@ describe("Slack Web API", () => {
40
62
  });
41
63
 
42
64
  it("creates a private channel, invites members, and posts the first message", async () => {
43
- mockAxiosPost.mockImplementation(async (url: string, body: {name?: string; text?: string}) => {
65
+ mockAxiosPost.mockImplementation(async (url: string, body: SlackRequestBody) => {
44
66
  if (String(url).endsWith("conversations.create")) {
45
67
  return {
46
68
  data: {channel: {id: "C012345678", is_private: true, name: body.name}, ok: true},
@@ -120,7 +142,7 @@ describe("Slack Web API", () => {
120
142
 
121
143
  expect(result.alreadyMemberUserIds).toEqual(["U012ABCDEF"]);
122
144
  expect(result.invitedUserIds).toEqual([]);
123
- const body = mockAxiosPost.mock.calls[0]?.[1] as {channel?: string; users?: string};
145
+ const body = mockAxiosPost.mock.calls[0]?.[1];
124
146
  expect(body).toEqual({channel: "C012345678", force: true, users: "U012ABCDEF"});
125
147
  });
126
148
 
@@ -211,8 +233,8 @@ describe("Slack Web API", () => {
211
233
 
212
234
  const found = await findSlackChannelByName({name: "case-123"});
213
235
  expect(found).toEqual({channelId: "C012345678", isPrivate: true, name: "case-123"});
214
- const firstParams = mockAxiosGet.mock.calls[0]?.[1] as {params?: {types?: string}};
215
- expect(firstParams.params?.types).toBe("public_channel,private_channel");
236
+ const firstParams = mockAxiosGet.mock.calls[0]?.[1];
237
+ expect(firstParams?.params?.types).toBe("public_channel,private_channel");
216
238
  });
217
239
 
218
240
  it("returns undefined when no visible channel has that name", async () => {