@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,194 @@
1
+ import {afterEach, beforeAll, beforeEach, describe, it} from "bun:test";
2
+ import {createHash, randomUUID} from "node:crypto";
3
+ import {assert} from "chai";
4
+ import {DateTime} from "luxon";
5
+ import mongoose from "mongoose";
6
+
7
+ import {McpServiceToken} from "../../models/mcpServiceToken";
8
+ import {clearSyncRegistry} from "../../sync/registry";
9
+ import {setupDb} from "../../tests";
10
+ import type {MigrationContext, MigrationLogger} from "../types";
11
+ import {
12
+ MCP_SERVICE_TOKEN_STRING_IDS_SLUG,
13
+ mcpServiceTokenStringIdsMigration,
14
+ migrateMcpServiceTokenStringIds,
15
+ } from "./mcpServiceTokenStringIds";
16
+
17
+ const hashToken = (token: string): string => createHash("sha256").update(token).digest("hex");
18
+
19
+ const silentLogger: MigrationLogger = {
20
+ debug: () => undefined,
21
+ error: () => undefined,
22
+ info: () => undefined,
23
+ warn: () => undefined,
24
+ };
25
+
26
+ const contextFor = (overrides: Partial<MigrationContext> = {}): MigrationContext => ({
27
+ dryRun: false,
28
+ logger: silentLogger,
29
+ mongoose,
30
+ ...overrides,
31
+ });
32
+
33
+ const tokens = (): mongoose.Collection => McpServiceToken.collection;
34
+
35
+ const legacyRow = (
36
+ plaintext: string,
37
+ userId: mongoose.Types.ObjectId,
38
+ extra: Record<string, unknown> = {}
39
+ ): Record<string, unknown> => ({
40
+ _id: new mongoose.Types.ObjectId(),
41
+ created: DateTime.now().minus({day: 3}).toJSDate(),
42
+ name: `Legacy ${plaintext.slice(-4)}`,
43
+ tokenHash: hashToken(plaintext),
44
+ tokenPrefix: plaintext.slice(4, 12),
45
+ updated: DateTime.now().minus({day: 3}).toJSDate(),
46
+ userId,
47
+ ...extra,
48
+ });
49
+
50
+ describe("mcp-service-token-string-ids migration", () => {
51
+ const userId = new mongoose.Types.ObjectId();
52
+ const activePlaintext = `mcp_${"a".repeat(64)}`;
53
+ const revokedPlaintext = `mcp_${"b".repeat(64)}`;
54
+ let active: Record<string, unknown>;
55
+ let revoked: Record<string, unknown>;
56
+
57
+ beforeAll(async () => {
58
+ await setupDb();
59
+ await McpServiceToken.syncIndexes();
60
+ }, 60_000);
61
+
62
+ beforeEach(async () => {
63
+ clearSyncRegistry();
64
+ await tokens().deleteMany({});
65
+ active = legacyRow(activePlaintext, userId);
66
+ revoked = legacyRow(revokedPlaintext, userId, {
67
+ revokedAt: DateTime.now().minus({day: 1}).toJSDate(),
68
+ });
69
+ await tokens().insertMany([active, revoked]);
70
+ });
71
+
72
+ afterEach(async () => {
73
+ await tokens().deleteMany({});
74
+ });
75
+
76
+ it("re-keys ObjectId rows to their hex string and is idempotent", async () => {
77
+ const issued = await McpServiceToken.issueFor({_id: userId}, {name: "Already a string"});
78
+
79
+ const first = await migrateMcpServiceTokenStringIds(contextFor());
80
+ const second = await migrateMcpServiceTokenStringIds(contextFor());
81
+
82
+ assert.deepEqual(first, {converted: 2, pending: 0});
83
+ assert.deepEqual(second, {converted: 0, pending: 0});
84
+ const rows = await tokens().find({}).toArray();
85
+ assert.lengthOf(rows, 3);
86
+ for (const row of rows) {
87
+ assert.isString(row._id);
88
+ }
89
+ assert.equal(await tokens().countDocuments({_id: {$type: "objectId"}}), 0);
90
+
91
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
92
+ const revokedId = (revoked._id as mongoose.Types.ObjectId).toHexString();
93
+ const migratedActive = await tokens().findOne({_id: activeId as never});
94
+ const migratedRevoked = await tokens().findOne({_id: revokedId as never});
95
+ assert.equal(migratedActive?.name, active.name);
96
+ assert.equal(migratedActive?.tokenHash, active.tokenHash);
97
+ assert.equal(String(migratedActive?.userId), String(userId));
98
+ assert.isFalse(migratedActive?.deleted);
99
+ assert.instanceOf(migratedRevoked?.revokedAt, Date);
100
+ assert.equal(await tokens().countDocuments({_id: issued.mcpServiceToken._id as never}), 1);
101
+ });
102
+
103
+ it("keeps migrated tokens verifiable and revocable by their hex id", async () => {
104
+ await migrateMcpServiceTokenStringIds(contextFor());
105
+
106
+ const verified = await McpServiceToken.verify(activePlaintext);
107
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
108
+ assert.equal(verified?._id, activeId);
109
+ assert.isNull(await McpServiceToken.verify(revokedPlaintext));
110
+
111
+ await McpServiceToken.revokeForUser({_id: userId}, activeId);
112
+ assert.isNull(await McpServiceToken.verify(activePlaintext));
113
+ });
114
+
115
+ it("finishes a row an interrupted run already parked and copied", async () => {
116
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
117
+ // Simulate a crash after the hash was parked and the copy inserted, before the delete.
118
+ await tokens().updateOne(
119
+ {_id: active._id as never},
120
+ {$set: {tokenHash: `${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}:${active.tokenHash}`}}
121
+ );
122
+ await tokens().insertOne({...active, _id: activeId as never, deleted: false});
123
+
124
+ const result = await migrateMcpServiceTokenStringIds(contextFor());
125
+
126
+ assert.equal(result.converted, 2);
127
+ assert.equal(await tokens().countDocuments({}), 2);
128
+ const migrated = await tokens().findOne({_id: activeId as never});
129
+ assert.equal(migrated?.tokenHash, active.tokenHash);
130
+ assert.equal((await McpServiceToken.verify(activePlaintext))?._id, activeId);
131
+ });
132
+
133
+ it("re-inserts a parked row whose copy never landed", async () => {
134
+ await tokens().updateOne(
135
+ {_id: active._id as never},
136
+ {$set: {tokenHash: `${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}:${active.tokenHash}`}}
137
+ );
138
+
139
+ await migrateMcpServiceTokenStringIds(contextFor());
140
+
141
+ const activeId = (active._id as mongoose.Types.ObjectId).toHexString();
142
+ const migrated = await tokens().findOne({_id: activeId as never});
143
+ assert.equal(migrated?.tokenHash, active.tokenHash);
144
+ assert.equal(await tokens().countDocuments({}), 2);
145
+ });
146
+
147
+ it("reports pending rows on a dry run without writing", async () => {
148
+ const logs: string[] = [];
149
+ const result = await migrateMcpServiceTokenStringIds(
150
+ contextFor({
151
+ dryRun: true,
152
+ logger: {...silentLogger, info: (message: string) => logs.push(message)},
153
+ })
154
+ );
155
+
156
+ assert.deepEqual(result, {converted: 0, pending: 2});
157
+ assert.equal(await tokens().countDocuments({_id: {$type: "objectId"}}), 2);
158
+ assert.match(logs[0] ?? "", /2 ObjectId rows would be re-keyed/);
159
+ });
160
+
161
+ it("exposes an up function for app migration files that logs progress", async () => {
162
+ const addLogCalls: string[] = [];
163
+ let cancellationChecks = 0;
164
+
165
+ await mcpServiceTokenStringIdsMigration.up(
166
+ contextFor({
167
+ addLog: async (_level, message) => {
168
+ addLogCalls.push(message);
169
+ },
170
+ checkCancellation: async () => {
171
+ cancellationChecks += 1;
172
+ },
173
+ })
174
+ );
175
+
176
+ assert.equal(mcpServiceTokenStringIdsMigration.slug, "mcp-service-token-string-ids");
177
+ assert.equal(await tokens().countDocuments({_id: {$type: "objectId"}}), 0);
178
+ assert.isAbove(cancellationChecks, 0);
179
+ assert.match(addLogCalls[0] ?? "", /re-keyed 2 rows/);
180
+ });
181
+
182
+ it("does nothing when every row already has a string id", async () => {
183
+ await tokens().deleteMany({});
184
+ await tokens().insertOne({
185
+ ...legacyRow(activePlaintext, userId),
186
+ _id: randomUUID() as never,
187
+ });
188
+
189
+ const result = await migrateMcpServiceTokenStringIds(contextFor());
190
+
191
+ assert.deepEqual(result, {converted: 0, pending: 0});
192
+ assert.equal(await tokens().countDocuments({}), 1);
193
+ });
194
+ });
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Built-in data migration for Terreno 58: McpServiceToken became a synced collection with
3
+ * String `_id`s. Rows minted before 58 have ObjectId `_id`s; this migration re-inserts each
4
+ * one with `_id = oldId.toHexString()` and deletes the original, so existing tokens keep
5
+ * the same id string clients already saw.
6
+ *
7
+ * Apps run it through their own `migrations/` directory (see `run-mongodb-migrations.md`):
8
+ *
9
+ * ```typescript
10
+ * // migrations/20261022120000-mcp-service-token-string-ids.ts
11
+ * import {mcpServiceTokenStringIdsMigration} from "@terreno/api";
12
+ *
13
+ * export const id = "20261022120000-mcp-service-token-string-ids";
14
+ * export const up = mcpServiceTokenStringIdsMigration.up;
15
+ * ```
16
+ *
17
+ * Idempotent: only ObjectId-keyed rows are selected, and a run interrupted mid-row resumes
18
+ * cleanly. It works on standalone servers (no transaction): the original row's unique
19
+ * `tokenHash` is parked behind a marker prefix before the copy is inserted, so a crash never
20
+ * loses a row. That token fails MCP auth only for the instant between park and copy.
21
+ */
22
+ import type mongoose from "mongoose";
23
+
24
+ import type {MigrationContext} from "../types";
25
+
26
+ export const MCP_SERVICE_TOKEN_STRING_IDS_SLUG = "mcp-service-token-string-ids";
27
+
28
+ const COLLECTION_NAME = "mcpservicetokens";
29
+ const BATCH_SIZE = 200;
30
+ const PARKED_HASH_PREFIX = "mcp-service-token-string-ids:";
31
+ const LEGACY_ID_FILTER = {_id: {$type: "objectId" as const}};
32
+
33
+ interface LegacyTokenRow {
34
+ _id: mongoose.Types.ObjectId;
35
+ deleted?: boolean;
36
+ tokenHash: string;
37
+ [key: string]: unknown;
38
+ }
39
+
40
+ export interface McpServiceTokenStringIdsResult {
41
+ /** Rows re-keyed to a String `_id` in this run. */
42
+ converted: number;
43
+ /** ObjectId-keyed rows still waiting (non-zero only for dry runs). */
44
+ pending: number;
45
+ }
46
+
47
+ const unparkedHash = (tokenHash: string): string =>
48
+ tokenHash.startsWith(PARKED_HASH_PREFIX) ? tokenHash.slice(PARKED_HASH_PREFIX.length) : tokenHash;
49
+
50
+ const convertRow = async ({
51
+ collection,
52
+ row,
53
+ }: {
54
+ collection: mongoose.Collection;
55
+ row: LegacyTokenRow;
56
+ }): Promise<void> => {
57
+ const stringId = row._id.toHexString();
58
+ const tokenHash = unparkedHash(row.tokenHash);
59
+ const parkedHash = `${PARKED_HASH_PREFIX}${tokenHash}`;
60
+ // Free the unique tokenHash for the copy while keeping the original row recoverable.
61
+ if (row.tokenHash !== parkedHash) {
62
+ await collection.updateOne({_id: row._id}, {$set: {tokenHash: parkedHash}});
63
+ }
64
+ const existingCopy = await collection.findOne({_id: stringId as never});
65
+ if (!existingCopy) {
66
+ await collection.insertOne({
67
+ ...row,
68
+ _id: stringId as never,
69
+ deleted: row.deleted ?? false,
70
+ tokenHash,
71
+ });
72
+ }
73
+ await collection.deleteOne({_id: row._id});
74
+ };
75
+
76
+ /**
77
+ * Re-key every ObjectId McpServiceToken row to its hex string. Returns how many rows were
78
+ * converted; a dry run converts nothing and reports how many are pending.
79
+ */
80
+ export const migrateMcpServiceTokenStringIds = async (
81
+ ctx: MigrationContext
82
+ ): Promise<McpServiceTokenStringIdsResult> => {
83
+ const collection = ctx.mongoose.connection.collection(COLLECTION_NAME);
84
+
85
+ if (ctx.dryRun) {
86
+ const pending = await collection.countDocuments(LEGACY_ID_FILTER);
87
+ ctx.logger.info(
88
+ `[${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}] dry run: ${pending} ObjectId rows would be re-keyed`
89
+ );
90
+ return {converted: 0, pending};
91
+ }
92
+
93
+ let converted = 0;
94
+ for (;;) {
95
+ await ctx.checkCancellation?.();
96
+ const batch = (await collection
97
+ .find(LEGACY_ID_FILTER)
98
+ .limit(BATCH_SIZE)
99
+ .toArray()) as unknown as LegacyTokenRow[];
100
+ if (batch.length === 0) {
101
+ break;
102
+ }
103
+ for (const row of batch) {
104
+ await convertRow({collection, row});
105
+ converted += 1;
106
+ }
107
+ }
108
+
109
+ const message = `[${MCP_SERVICE_TOKEN_STRING_IDS_SLUG}] re-keyed ${converted} rows to String ids`;
110
+ ctx.logger.info(message);
111
+ await ctx.addLog?.("info", message);
112
+ return {converted, pending: 0};
113
+ };
114
+
115
+ /** Ready-made `up` for an app migration file (irreversible: new rows use UUID ids). */
116
+ export const mcpServiceTokenStringIdsMigration = {
117
+ slug: MCP_SERVICE_TOKEN_STRING_IDS_SLUG,
118
+ up: async (ctx: MigrationContext): Promise<void> => {
119
+ await migrateMcpServiceTokenStringIds(ctx);
120
+ },
121
+ };
@@ -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>(