@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,230 @@
1
+ import {afterEach, beforeEach, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type express from "express";
4
+ import type mongoose from "mongoose";
5
+ import type {Server} from "socket.io";
6
+ import type TestAgent from "supertest/lib/agent";
7
+
8
+ import type {UserModel as AuthUserModel} from "../auth";
9
+ import {McpServiceToken} from "../models/mcpServiceToken";
10
+ import {emitSyncDeltaForChange} from "../realtime/changeStreamWatcher";
11
+ import {
12
+ clearSyncRegistry,
13
+ findSyncEntryByCollectionTag,
14
+ type SyncRegistryEntry,
15
+ } from "../sync/registry";
16
+ import {syncRoomForStream} from "../sync/socketHandlers";
17
+ import {SyncApp} from "../sync/syncApp";
18
+ import type {SyncDelta, SyncSnapshotResponse} from "../sync/types";
19
+ import {TerrenoApp} from "../terrenoApp";
20
+ import {authAsUser, setupDb, UserModel} from "../tests";
21
+ import {MCP_SERVICE_TOKENS_SYNC_COLLECTION} from "./serviceTokens";
22
+
23
+ interface CreatedToken {
24
+ id: string;
25
+ token: string;
26
+ }
27
+
28
+ interface TrackedEmission {
29
+ event: string;
30
+ payload: unknown;
31
+ }
32
+
33
+ const buildApp = (): express.Application => {
34
+ clearSyncRegistry();
35
+ return new TerrenoApp({
36
+ mcpServiceTokens: true,
37
+ skipListen: true,
38
+ userModel: UserModel as unknown as AuthUserModel,
39
+ })
40
+ .register(new SyncApp({}))
41
+ .build();
42
+ };
43
+
44
+ const ownerStream = (userId: string): string =>
45
+ `${MCP_SERVICE_TOKENS_SYNC_COLLECTION}|owner:${userId}`;
46
+
47
+ /** Socket.io stand-in with one socket for `userId` joined to `room`. */
48
+ const makeTrackedIo = (
49
+ room: string,
50
+ userId: string
51
+ ): {emissions: TrackedEmission[]; io: Server} => {
52
+ const emissions: TrackedEmission[] = [];
53
+ const socket = {
54
+ decodedToken: {admin: false, id: userId},
55
+ emit: (event: string, payload: unknown): void => {
56
+ emissions.push({event, payload});
57
+ },
58
+ id: "socket-owner",
59
+ };
60
+ const io = {
61
+ sockets: {
62
+ adapter: {rooms: new Map([[room, new Set([socket.id])]])},
63
+ sockets: new Map([[socket.id, socket]]),
64
+ },
65
+ to: () => ({emit: (): void => undefined}),
66
+ } as unknown as Server;
67
+ return {emissions, io};
68
+ };
69
+
70
+ const assertNoTokenSecrets = (value: unknown, plaintext: string): void => {
71
+ const serialized = JSON.stringify(value);
72
+ assert.notInclude(serialized, "tokenHash");
73
+ assert.notInclude(serialized, plaintext);
74
+ };
75
+
76
+ describe("MCP service tokens as a synced collection", () => {
77
+ let agent: TestAgent;
78
+ let otherAgent: TestAgent;
79
+ let ownerId: string;
80
+ let created: CreatedToken;
81
+
82
+ beforeEach(async () => {
83
+ const [admin, notAdmin] = await setupDb();
84
+ ownerId = String((notAdmin as {_id: mongoose.Types.ObjectId})._id);
85
+ await McpServiceToken.collection.deleteMany({});
86
+ const app = buildApp();
87
+ agent = await authAsUser(app, "notAdmin");
88
+ otherAgent = await authAsUser(app, "admin");
89
+ assert.isDefined(admin);
90
+ const res = await agent.post("/mcp/service-tokens/create").send({name: "Synced"});
91
+ assert.equal(res.status, 200);
92
+ created = res.body.data as CreatedToken;
93
+ });
94
+
95
+ afterEach(async () => {
96
+ await McpServiceToken.collection.deleteMany({});
97
+ clearSyncRegistry();
98
+ });
99
+
100
+ it("serves the owner's snapshot without tokenHash or the plaintext", async () => {
101
+ const res = await agent.get(
102
+ `/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}`
103
+ );
104
+
105
+ assert.equal(res.status, 200);
106
+ const page = res.body as SyncSnapshotResponse;
107
+ assert.lengthOf(page.entities, 1);
108
+ const [entity] = page.entities;
109
+ assert.equal(entity.id, created.id);
110
+ assert.isAbove(entity.seq, 0);
111
+ const data = entity.data as Record<string, unknown>;
112
+ assert.equal(data.name, "Synced");
113
+ assert.equal(data.id, created.id);
114
+ assert.equal(data.tokenPrefix, created.token.slice(4, 12));
115
+ assert.notProperty(data, "tokenHash");
116
+ assert.notProperty(data, "token");
117
+ assertNoTokenSecrets(res.body, created.token);
118
+ });
119
+
120
+ it("strips tokenHash from batched snapshots and entity lookups", async () => {
121
+ const batch = await agent
122
+ .post("/sync/snapshot/batch")
123
+ .send({streams: [{stream: ownerStream(ownerId)}]});
124
+ const entities = await agent.get(
125
+ `/sync/entities?collection=${encodeURIComponent(MCP_SERVICE_TOKENS_SYNC_COLLECTION)}&ids=${created.id}`
126
+ );
127
+
128
+ assert.equal(batch.status, 200);
129
+ assert.equal(entities.status, 200);
130
+ assert.lengthOf(batch.body.pages[0].entities, 1);
131
+ assert.lengthOf(entities.body.entities, 1);
132
+ assertNoTokenSecrets(batch.body, created.token);
133
+ assertNoTokenSecrets(entities.body, created.token);
134
+ });
135
+
136
+ it("does not serve another user's stream", async () => {
137
+ const res = await otherAgent.get(
138
+ `/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}`
139
+ );
140
+
141
+ assert.equal(res.status, 403);
142
+ assertNoTokenSecrets(res.body, created.token);
143
+ });
144
+
145
+ it("emits deltas without tokenHash", async () => {
146
+ const entry = findSyncEntryByCollectionTag(
147
+ MCP_SERVICE_TOKENS_SYNC_COLLECTION
148
+ ) as SyncRegistryEntry;
149
+ // The change stream post-image is the raw stored row, tokenHash included.
150
+ const fullDocument = (await McpServiceToken.collection.findOne({
151
+ _id: created.id as never,
152
+ })) as Record<string, unknown>;
153
+ assert.isString(fullDocument.tokenHash);
154
+ const stream = ownerStream(ownerId);
155
+ const {emissions, io} = makeTrackedIo(syncRoomForStream(stream), ownerId);
156
+
157
+ await emitSyncDeltaForChange({
158
+ change: {
159
+ documentKey: {_id: created.id},
160
+ fullDocument,
161
+ ns: {coll: "mcpservicetokens"},
162
+ operationType: "insert",
163
+ } as unknown as Parameters<typeof emitSyncDeltaForChange>[0]["change"],
164
+ docId: created.id,
165
+ entry,
166
+ io,
167
+ logDebug: () => undefined,
168
+ });
169
+
170
+ const delta = emissions.find((emission) => emission.event === "sync:delta")
171
+ ?.payload as SyncDelta;
172
+ assert.isDefined(delta);
173
+ assert.equal(delta.stream, stream);
174
+ const data = delta.data as Record<string, unknown>;
175
+ assert.equal(data.name, "Synced");
176
+ assert.notProperty(data, "tokenHash");
177
+ assertNoTokenSecrets(delta, created.token);
178
+ });
179
+
180
+ it("rejects client sync create, update, and delete", async () => {
181
+ const stored = await McpServiceToken.collection.findOne({_id: created.id as never});
182
+ const baseVersion = stored?._syncSeq as number;
183
+ const attempts = [
184
+ {
185
+ data: {name: "Forged", tokenHash: "forged", tokenPrefix: "forged", userId: ownerId},
186
+ mutationId: "mcp-token-create",
187
+ operation: "create",
188
+ },
189
+ {
190
+ baseVersion,
191
+ data: {name: "Renamed"},
192
+ id: created.id,
193
+ mutationId: "mcp-token-update",
194
+ operation: "update",
195
+ },
196
+ {id: created.id, mutationId: "mcp-token-delete", operation: "delete"},
197
+ ];
198
+
199
+ for (const attempt of attempts) {
200
+ const res = await agent
201
+ .post("/sync/mutate")
202
+ .send({...attempt, collection: MCP_SERVICE_TOKENS_SYNC_COLLECTION});
203
+ assert.equal(res.status, 403, attempt.operation);
204
+ assert.equal(res.body.nack?.code, "unauthorized", attempt.operation);
205
+ }
206
+
207
+ const rows = await McpServiceToken.collection.find({}).toArray();
208
+ assert.lengthOf(rows, 1);
209
+ assert.equal(rows[0].name, "Synced");
210
+ assert.notOk(rows[0].revokedAt);
211
+ assert.isFalse(rows[0].deleted);
212
+ });
213
+
214
+ it("syncs a revoke as an update that keeps the row", async () => {
215
+ const before = await agent.get(
216
+ `/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}`
217
+ );
218
+ const revoked = await agent.post(`/mcp/service-tokens/${created.id}/revoke`);
219
+ const after = await agent.get(
220
+ `/sync/snapshot?stream=${encodeURIComponent(ownerStream(ownerId))}&cursor=${before.body.cursor}`
221
+ );
222
+
223
+ assert.equal(revoked.status, 200);
224
+ assert.lengthOf(after.body.entities, 1);
225
+ const [entity] = after.body.entities as SyncSnapshotResponse["entities"];
226
+ assert.isFalse(entity.deleted);
227
+ assert.isString((entity.data as {revokedAt?: unknown}).revokedAt);
228
+ assertNoTokenSecrets(after.body, created.token);
229
+ });
230
+ });
@@ -9,11 +9,19 @@ import type TestAgent from "supertest/lib/agent";
9
9
  import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "../auth";
10
10
  import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "../errors";
11
11
  import {McpServiceToken} from "../models/mcpServiceToken";
12
+ import {clearSyncRegistry} from "../sync/registry";
12
13
  import {TerrenoApp} from "../terrenoApp";
13
14
  import {authAsUser, getBaseServer, setupDb, UserModel} from "../tests";
14
15
  import {addMcpServiceTokenRoutes, MAX_ACTIVE_MCP_SERVICE_TOKENS} from "./serviceTokens";
15
16
 
16
17
  const PUBLIC_MCP_URL = "https://api.example.com";
18
+ const CREATE_PATH = "/mcp/service-tokens/create";
19
+ const revokePath = (id: string): string => `/mcp/service-tokens/${id}/revoke`;
20
+
21
+ // The collection is synced once the router registers, and syncPlugin rejects Model.deleteMany.
22
+ const clearTokens = async (): Promise<void> => {
23
+ await McpServiceToken.collection.deleteMany({});
24
+ };
17
25
 
18
26
  const assertNoSecrets = (body: unknown): void => {
19
27
  const serialized = JSON.stringify(body);
@@ -38,7 +46,7 @@ describe("MCP service token routes", () => {
38
46
  beforeEach(async () => {
39
47
  const users = await setupDb();
40
48
  notAdminId = users[1]._id as mongoose.Types.ObjectId;
41
- await McpServiceToken.deleteMany({});
49
+ await clearTokens();
42
50
 
43
51
  app = getBaseServer();
44
52
  setupAuth(app, UserModel as never);
@@ -51,8 +59,13 @@ describe("MCP service token routes", () => {
51
59
  adminAgent = await authAsUser(app, "admin");
52
60
  });
53
61
 
62
+ afterEach(async () => {
63
+ await clearTokens();
64
+ clearSyncRegistry();
65
+ });
66
+
54
67
  it("creates a token once and returns mcpUrl with the plaintext", async () => {
55
- const res = await agent.post("/mcp/service-tokens").send({name: "Perplexity laptop"});
68
+ const res = await agent.post(CREATE_PATH).send({name: "Perplexity laptop"});
56
69
 
57
70
  assert.equal(res.status, 200);
58
71
  assert.match(res.body.data.token, /^mcp_[0-9a-f]{64}$/);
@@ -62,19 +75,63 @@ describe("MCP service token routes", () => {
62
75
  assert.isUndefined(res.body.data.tokenHash);
63
76
 
64
77
  const stored = await McpServiceToken.findExactlyOne({_id: res.body.data.id});
78
+ assert.isString(stored._id);
65
79
  assert.notEqual(stored.tokenHash, res.body.data.token);
66
80
  assert.notInclude(JSON.stringify(stored.toJSON()), res.body.data.token);
67
81
  });
68
82
 
83
+ it("returns the plaintext only from create, never from list or read", async () => {
84
+ const created = await agent.post(CREATE_PATH).send({name: "Once"});
85
+ const plaintext = created.body.data.token as string;
86
+ assert.match(plaintext, /^mcp_[0-9a-f]{64}$/);
87
+
88
+ const listed = await agent.get("/mcp/service-tokens");
89
+ const read = await agent.get(`/mcp/service-tokens/${created.body.data.id}`);
90
+
91
+ assert.equal(read.status, 200);
92
+ for (const res of [listed, read]) {
93
+ assert.notInclude(JSON.stringify(res.body), plaintext);
94
+ assertNoSecrets(res.body);
95
+ }
96
+ assert.notProperty(read.body.data, "token");
97
+ assert.notProperty(read.body.data, "tokenHash");
98
+ });
99
+
100
+ it("disables REST create, update, and delete on the collection", async () => {
101
+ const created = await agent.post(CREATE_PATH).send({name: "Locked"});
102
+ const tokenId = created.body.data.id as string;
103
+
104
+ const rawCreate = await agent
105
+ .post("/mcp/service-tokens")
106
+ .send({name: "Raw", tokenHash: "x", tokenPrefix: "x", userId: String(notAdminId)});
107
+ const update = await agent.patch(`/mcp/service-tokens/${tokenId}`).send({name: "Renamed"});
108
+ const remove = await agent.delete(`/mcp/service-tokens/${tokenId}`);
109
+
110
+ assert.equal(rawCreate.status, 405);
111
+ assert.equal(update.status, 405);
112
+ assert.equal(remove.status, 405);
113
+ const stored = await McpServiceToken.findExactlyOne({_id: tokenId});
114
+ assert.equal(stored.name, "Locked");
115
+ assert.isUndefined(stored.revokedAt);
116
+ });
117
+
118
+ it("does not let another user read a token", async () => {
119
+ const created = await agent.post(CREATE_PATH).send({name: "Private"});
120
+
121
+ const res = await adminAgent.get(`/mcp/service-tokens/${created.body.data.id}`);
122
+
123
+ assert.equal(res.status, 403);
124
+ assertNoSecrets(res.body);
125
+ });
126
+
69
127
  it("lists only the caller's tokens without plaintext or hash", async () => {
70
- const mine = await agent.post("/mcp/service-tokens").send({name: "Mine"});
71
- await adminAgent.post("/mcp/service-tokens").send({name: "Admin token"});
128
+ const mine = await agent.post(CREATE_PATH).send({name: "Mine"});
129
+ await adminAgent.post(CREATE_PATH).send({name: "Admin token"});
72
130
 
73
131
  const res = await agent.get("/mcp/service-tokens");
74
132
 
75
133
  assert.equal(res.status, 200);
76
134
  assert.equal(res.body.total, 1);
77
- assert.equal(res.body.page, 1);
78
135
  assert.equal(res.body.more, false);
79
136
  assert.equal(res.body.data.length, 1);
80
137
  assert.equal(res.body.data[0].id, mine.body.data.id);
@@ -84,7 +141,7 @@ describe("MCP service token routes", () => {
84
141
 
85
142
  it("accepts an optional future ISO expiresAt on create", async () => {
86
143
  const expiresAt = DateTime.now().plus({day: 1}).toUTC().toISO();
87
- const res = await agent.post("/mcp/service-tokens").send({
144
+ const res = await agent.post(CREATE_PATH).send({
88
145
  expiresAt,
89
146
  name: "Expiring",
90
147
  });
@@ -94,22 +151,24 @@ describe("MCP service token routes", () => {
94
151
  });
95
152
 
96
153
  it("revokes an owned token and hides it from other users", async () => {
97
- const created = await agent.post("/mcp/service-tokens").send({name: "To revoke"});
154
+ const created = await agent.post(CREATE_PATH).send({name: "To revoke"});
98
155
  const tokenId = created.body.data.id as string;
99
156
 
100
- const otherDelete = await adminAgent.delete(`/mcp/service-tokens/${tokenId}`);
101
- assert.equal(otherDelete.status, 404);
157
+ const otherRevoke = await adminAgent.post(revokePath(tokenId));
158
+ assert.equal(otherRevoke.status, 404);
102
159
 
103
- const revoked = await agent.delete(`/mcp/service-tokens/${tokenId}`);
160
+ const revoked = await agent.post(revokePath(tokenId));
104
161
  assert.equal(revoked.status, 200);
105
162
  assert.equal(revoked.body.data.id, tokenId);
106
163
  assert.isString(revoked.body.data.revokedAt);
164
+ assertNoSecrets(revoked.body);
165
+ assert.notProperty(revoked.body.data, "tokenHash");
107
166
 
108
167
  const listed = await agent.get("/mcp/service-tokens");
109
168
  assert.equal(listed.body.data[0].id, tokenId);
110
169
  assert.isString(listed.body.data[0].revokedAt);
111
170
 
112
- const again = await agent.delete(`/mcp/service-tokens/${tokenId}`);
171
+ const again = await agent.post(revokePath(tokenId));
113
172
  assert.equal(again.status, 404);
114
173
  });
115
174
 
@@ -118,7 +177,7 @@ describe("MCP service token routes", () => {
118
177
  await McpServiceToken.issueFor({_id: notAdminId}, {name: `Token ${index}`});
119
178
  }
120
179
 
121
- const res = await agent.post("/mcp/service-tokens").send({name: "One too many"});
180
+ const res = await agent.post(CREATE_PATH).send({name: "One too many"});
122
181
 
123
182
  assert.equal(res.status, 400);
124
183
  assert.match(res.body.title, /Maximum of 10 active MCP service tokens/);
@@ -126,18 +185,18 @@ describe("MCP service token routes", () => {
126
185
  });
127
186
 
128
187
  it("rejects mcp_ bearer tokens on self-serve routes", async () => {
129
- const created = await agent.post("/mcp/service-tokens").send({name: "Connector"});
188
+ const created = await agent.post(CREATE_PATH).send({name: "Connector"});
130
189
  const mcpToken = created.body.data.token as string;
131
190
 
132
191
  const listed = await supertest(app)
133
192
  .get("/mcp/service-tokens")
134
193
  .set("Authorization", `Bearer ${mcpToken}`);
135
194
  const minted = await supertest(app)
136
- .post("/mcp/service-tokens")
195
+ .post(CREATE_PATH)
137
196
  .set("Authorization", `Bearer ${mcpToken}`)
138
197
  .send({name: "Nested"});
139
198
  const revoked = await supertest(app)
140
- .delete(`/mcp/service-tokens/${created.body.data.id}`)
199
+ .post(revokePath(created.body.data.id))
141
200
  .set("Authorization", `Bearer ${mcpToken}`);
142
201
 
143
202
  assert.equal(listed.status, 401);
@@ -151,19 +210,17 @@ describe("MCP service token routes", () => {
151
210
  });
152
211
 
153
212
  it("returns 404 for an unknown token id", async () => {
154
- const res = await agent.delete(
155
- `/mcp/service-tokens/${new mongoose.Types.ObjectId().toString()}`
156
- );
213
+ const res = await agent.post(revokePath(new mongoose.Types.ObjectId().toString()));
157
214
  assert.equal(res.status, 404);
158
215
  });
159
216
 
160
217
  it("returns 404 for a malformed token id", async () => {
161
- const res = await agent.delete("/mcp/service-tokens/not-an-object-id");
218
+ const res = await agent.post(revokePath("not-an-object-id"));
162
219
  assert.equal(res.status, 404);
163
220
  });
164
221
 
165
222
  it("rejects a raw mcp_ authorization header without the Bearer prefix", async () => {
166
- const created = await agent.post("/mcp/service-tokens").send({name: "Raw"});
223
+ const created = await agent.post(CREATE_PATH).send({name: "Raw"});
167
224
  const mcpToken = created.body.data.token as string;
168
225
 
169
226
  const res = await supertest(app).get("/mcp/service-tokens").set("Authorization", mcpToken);
@@ -171,18 +228,21 @@ describe("MCP service token routes", () => {
171
228
  });
172
229
 
173
230
  it("rejects a missing, non-string, or blank name", async () => {
174
- const missing = await agent.post("/mcp/service-tokens").send({});
175
- const nonString = await agent.post("/mcp/service-tokens").send({name: 42});
176
- const blank = await agent.post("/mcp/service-tokens").send({name: " "});
231
+ const missing = await agent.post(CREATE_PATH).send({});
232
+ const nonString = await agent.post(CREATE_PATH).send({name: 42});
233
+ const blank = await agent.post(CREATE_PATH).send({name: " "});
177
234
 
178
- for (const res of [missing, nonString, blank]) {
235
+ for (const res of [missing, nonString]) {
179
236
  assert.equal(res.status, 400);
180
- assert.equal(res.body.title, "name is required");
237
+ assert.equal(res.body.title, "Validation failed");
181
238
  }
239
+ assert.equal(blank.status, 400);
240
+ assert.equal(blank.body.title, "name is required");
241
+ assert.equal(await McpServiceToken.countActiveForUser(notAdminId), 0);
182
242
  });
183
243
 
184
244
  it("trims the name and treats an empty expiresAt as unset", async () => {
185
- const res = await agent.post("/mcp/service-tokens").send({expiresAt: "", name: " Padded "});
245
+ const res = await agent.post(CREATE_PATH).send({expiresAt: "", name: " Padded "});
186
246
 
187
247
  assert.equal(res.status, 200);
188
248
  assert.equal(res.body.data.name, "Padded");
@@ -190,42 +250,26 @@ describe("MCP service token routes", () => {
190
250
  });
191
251
 
192
252
  it("rejects non-string, invalid, and past expiresAt values", async () => {
193
- const nonString = await agent.post("/mcp/service-tokens").send({expiresAt: 123, name: "A"});
194
- const invalid = await agent
195
- .post("/mcp/service-tokens")
196
- .send({expiresAt: "not-a-date", name: "B"});
197
- const past = await agent.post("/mcp/service-tokens").send({
253
+ const nonString = await agent.post(CREATE_PATH).send({expiresAt: 123, name: "A"});
254
+ const invalid = await agent.post(CREATE_PATH).send({expiresAt: "not-a-date", name: "B"});
255
+ const past = await agent.post(CREATE_PATH).send({
198
256
  expiresAt: DateTime.now().minus({day: 1}).toUTC().toISO(),
199
257
  name: "C",
200
258
  });
201
259
 
202
260
  assert.equal(nonString.status, 400);
203
- assert.equal(nonString.body.title, "expiresAt must be an ISO-8601 datetime string");
261
+ assert.equal(nonString.body.title, "Validation failed");
204
262
  assert.equal(invalid.status, 400);
205
263
  assert.equal(invalid.body.title, "expiresAt must be an ISO-8601 datetime string");
206
264
  assert.equal(past.status, 400);
207
265
  assert.equal(past.body.title, "expiresAt must be in the future");
208
266
  });
209
267
 
210
- it("validates and applies page and limit on list", async () => {
268
+ it("applies page and limit on list and caps the limit at 100", async () => {
211
269
  for (const name of ["One", "Two", "Three"]) {
212
- await agent.post("/mcp/service-tokens").send({name});
270
+ await agent.post(CREATE_PATH).send({name});
213
271
  }
214
272
 
215
- const badPage = await agent.get("/mcp/service-tokens?page=0");
216
- assert.equal(badPage.status, 400);
217
- assert.equal(badPage.body.title, "Invalid page");
218
-
219
- const fractionalPage = await agent.get("/mcp/service-tokens?page=1.5");
220
- assert.equal(fractionalPage.status, 400);
221
-
222
- const badLimit = await agent.get("/mcp/service-tokens?limit=abc");
223
- assert.equal(badLimit.status, 400);
224
- assert.equal(badLimit.body.title, "Invalid limit");
225
-
226
- const zeroLimit = await agent.get("/mcp/service-tokens?limit=0");
227
- assert.equal(zeroLimit.status, 400);
228
-
229
273
  const paged = await agent.get("/mcp/service-tokens?page=2&limit=2");
230
274
  assert.equal(paged.status, 200);
231
275
  assert.equal(paged.body.page, 2);
@@ -236,7 +280,7 @@ describe("MCP service token routes", () => {
236
280
 
237
281
  const capped = await agent.get("/mcp/service-tokens?limit=10000");
238
282
  assert.equal(capped.status, 200);
239
- assert.isBelow(capped.body.limit, 10000);
283
+ assert.equal(capped.body.limit, 100);
240
284
  });
241
285
  });
242
286
 
@@ -255,10 +299,11 @@ describe("MCP service token mcpUrl resolution", () => {
255
299
 
256
300
  beforeEach(async () => {
257
301
  await setupDb();
258
- await McpServiceToken.deleteMany({});
302
+ await clearTokens();
259
303
  });
260
304
 
261
305
  afterEach(() => {
306
+ clearSyncRegistry();
262
307
  if (originalBetterAuthUrl === undefined) {
263
308
  delete process.env.BETTER_AUTH_URL;
264
309
  } else {
@@ -270,7 +315,7 @@ describe("MCP service token mcpUrl resolution", () => {
270
315
  const app = buildApp("https://api.example.com/mcp/");
271
316
  const agent = await authAsUser(app, "notAdmin");
272
317
 
273
- const res = await agent.post("/mcp/service-tokens").send({name: "Configured"});
318
+ const res = await agent.post(CREATE_PATH).send({name: "Configured"});
274
319
 
275
320
  assert.equal(res.status, 200);
276
321
  assert.equal(res.body.data.mcpUrl, "https://api.example.com/mcp");
@@ -281,7 +326,7 @@ describe("MCP service token mcpUrl resolution", () => {
281
326
  const app = buildApp();
282
327
  const agent = await authAsUser(app, "notAdmin");
283
328
 
284
- const res = await agent.post("/mcp/service-tokens").send({name: "Env"});
329
+ const res = await agent.post(CREATE_PATH).send({name: "Env"});
285
330
 
286
331
  assert.equal(res.status, 200);
287
332
  assert.equal(res.body.data.mcpUrl, "https://auth.example.com/mcp");
@@ -292,7 +337,7 @@ describe("MCP service token mcpUrl resolution", () => {
292
337
  const app = buildApp();
293
338
  const agent = await authAsUser(app, "notAdmin");
294
339
 
295
- const res = await agent.post("/mcp/service-tokens").send({name: "Host"});
340
+ const res = await agent.post(CREATE_PATH).send({name: "Host"});
296
341
 
297
342
  assert.equal(res.status, 200);
298
343
  assert.match(res.body.data.mcpUrl, /^http:\/\/127\.0\.0\.1:\d+\/mcp$/);
@@ -300,10 +345,15 @@ describe("MCP service token mcpUrl resolution", () => {
300
345
  });
301
346
 
302
347
  describe("MCP service token OpenAPI", () => {
348
+ afterEach(() => {
349
+ clearSyncRegistry();
350
+ });
351
+
303
352
  it("documents create, list, and revoke on /openapi.json", async () => {
304
353
  const app = new TerrenoApp({
305
354
  configureApp: (router, options) => {
306
- addMcpServiceTokenRoutes(router, {
355
+ // The routes only call get/post/delete, which the configureApp router provides.
356
+ addMcpServiceTokenRoutes(router as unknown as express.Application, {
307
357
  openApi: options?.openApi,
308
358
  publicMcpUrl: PUBLIC_MCP_URL,
309
359
  });
@@ -315,16 +365,18 @@ describe("MCP service token OpenAPI", () => {
315
365
  const res = await supertest(app).get("/openapi.json");
316
366
 
317
367
  assert.equal(res.status, 200);
318
- assert.equal(res.body.paths["/mcp/service-tokens"].post.operationId, "createMcpServiceToken");
319
- assert.equal(res.body.paths["/mcp/service-tokens"].get.operationId, "listMcpServiceTokens");
320
- assert.equal(
321
- res.body.paths["/mcp/service-tokens/{id}"].delete.operationId,
322
- "revokeMcpServiceToken"
368
+ const create = res.body.paths["/mcp/service-tokens/create"].post;
369
+ assert.equal(create.operationId, "mcpServiceTokens_create");
370
+ assert.property(
371
+ create.responses["200"].content["application/json"].schema.properties.data.properties,
372
+ "token"
323
373
  );
324
374
  assert.equal(
325
- res.body.paths["/mcp/service-tokens"].post.responses["200"].content["application/json"].schema
326
- .properties.data.type,
327
- "object"
375
+ res.body.paths["/mcp/service-tokens/{id}/revoke"].post.operationId,
376
+ "mcpServiceTokens_revoke"
328
377
  );
378
+ const list = res.body.paths["/mcp/service-tokens/"].get;
379
+ assert.deepEqual(list["x-terreno-sync"], {collection: "mcp/service-tokens", scope: "owner"});
380
+ assert.notProperty(res.body.paths["/mcp/service-tokens/"], "post");
329
381
  });
330
382
  });