@terreno/api 57.19.2 → 57.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/biome.jsonc +1 -0
  3. package/dist/accountSecurity/accessActions.d.ts +38 -0
  4. package/dist/accountSecurity/accessActions.js +157 -0
  5. package/dist/accountSecurity/accountSecurityApp.d.ts +219 -0
  6. package/dist/accountSecurity/accountSecurityApp.js +438 -0
  7. package/dist/accountSecurity/accountSecurityService.d.ts +200 -0
  8. package/dist/accountSecurity/accountSecurityService.js +481 -0
  9. package/dist/accountSecurity/credentialActions.d.ts +16 -0
  10. package/dist/accountSecurity/credentialActions.js +189 -0
  11. package/dist/accountSecurity/membershipActions.d.ts +15 -0
  12. package/dist/accountSecurity/membershipActions.js +81 -0
  13. package/dist/accountSecurity/orgSecurityRoutes.d.ts +50 -0
  14. package/dist/accountSecurity/orgSecurityRoutes.js +149 -0
  15. package/dist/accountSecurity/securityEventHooks.d.ts +44 -0
  16. package/dist/accountSecurity/securityEventHooks.js +223 -0
  17. package/dist/accountSecurity/securityEvents.d.ts +162 -0
  18. package/dist/accountSecurity/securityEvents.js +114 -0
  19. package/dist/accountSecurity/securityNotifications.d.ts +125 -0
  20. package/dist/accountSecurity/securityNotifications.js +333 -0
  21. package/dist/api.d.ts +3 -3
  22. package/dist/api.js +38 -6
  23. package/dist/audit/auditEventModel.d.ts +5 -3
  24. package/dist/audit/auditEventModel.js +8 -6
  25. package/dist/audit/processQueue.js +4 -2
  26. package/dist/audit/record.d.ts +2 -2
  27. package/dist/audit/record.js +3 -0
  28. package/dist/authRecovery.js +29 -1
  29. package/dist/betterAuth.d.ts +179 -10
  30. package/dist/betterAuthApp.d.ts +15 -0
  31. package/dist/betterAuthApp.js +23 -0
  32. package/dist/betterAuthChallengeHeaders.d.ts +37 -0
  33. package/dist/betterAuthChallengeHeaders.js +180 -0
  34. package/dist/betterAuthFeatures.d.ts +54 -0
  35. package/dist/betterAuthFeatures.js +239 -0
  36. package/dist/betterAuthMethods.d.ts +73 -0
  37. package/dist/betterAuthMethods.js +55 -0
  38. package/dist/betterAuthOAuthHandoff.d.ts +10 -2
  39. package/dist/betterAuthOAuthHandoff.js +222 -24
  40. package/dist/betterAuthSetPassword.d.ts +33 -0
  41. package/dist/betterAuthSetPassword.js +166 -0
  42. package/dist/betterAuthSetup.d.ts +57 -8
  43. package/dist/betterAuthSetup.js +327 -36
  44. package/dist/consentApp.d.ts +9 -4
  45. package/dist/consentApp.js +344 -28
  46. package/dist/consentStatus.d.ts +60 -0
  47. package/dist/consentStatus.js +111 -0
  48. package/dist/errors.d.ts +6 -0
  49. package/dist/errors.js +41 -2
  50. package/dist/expressServer.js +3 -2
  51. package/dist/frameworkModelNames.d.ts +4 -0
  52. package/dist/frameworkModelNames.js +4 -0
  53. package/dist/index.d.ts +18 -2
  54. package/dist/index.js +29 -3
  55. package/dist/mcp/adminTracking.d.ts +28 -0
  56. package/dist/mcp/adminTracking.js +80 -0
  57. package/dist/mcp/auth.d.ts +6 -0
  58. package/dist/mcp/auth.js +12 -2
  59. package/dist/mcp/oauth.js +151 -11
  60. package/dist/mcp/oauthMetadata.d.ts +2 -1
  61. package/dist/mcp/oauthMetadata.js +7 -4
  62. package/dist/mcp/server.d.ts +8 -0
  63. package/dist/mcp/server.js +48 -4
  64. package/dist/models/consentResponse.js +51 -0
  65. package/dist/models/mcpOAuthClient.js +78 -2
  66. package/dist/models/mcpOAuthToken.js +55 -4
  67. package/dist/models/mcpRequestLog.d.ts +2 -0
  68. package/dist/models/mcpRequestLog.js +73 -0
  69. package/dist/models/mcpServiceToken.js +4 -0
  70. package/dist/models/mcpToolSetting.d.ts +2 -0
  71. package/dist/models/mcpToolSetting.js +119 -0
  72. package/dist/models/versionConfig.d.ts +2 -0
  73. package/dist/orgs/membershipGuards.d.ts +7 -0
  74. package/dist/orgs/membershipGuards.js +32 -0
  75. package/dist/orgs/orgsApp.d.ts +19 -1
  76. package/dist/orgs/orgsApp.js +55 -24
  77. package/dist/rateLimit/policies.js +8 -0
  78. package/dist/rbac/access.js +2 -1
  79. package/dist/rbac/auditModel.d.ts +2 -1
  80. package/dist/rbac/resolve.d.ts +9 -1
  81. package/dist/rbac/resolve.js +21 -16
  82. package/dist/rbac/roleManager.d.ts +6 -0
  83. package/dist/rbac/roleManager.js +8 -7
  84. package/dist/rbac/roleModel.d.ts +1 -0
  85. package/dist/rbac/roleModel.js +45 -3
  86. package/dist/rbac/statements.d.ts +2 -2
  87. package/dist/rbac/statements.js +10 -1
  88. package/dist/rbac/types.d.ts +6 -0
  89. package/dist/rbac/userWriteGuards.js +2 -1
  90. package/dist/schemaMetadata.js +8 -1
  91. package/dist/seedRunner.js +7 -2
  92. package/dist/terrenoApp.d.ts +16 -0
  93. package/dist/terrenoApp.js +18 -0
  94. package/dist/tests/models.d.ts +22 -22
  95. package/dist/tests/models.js +15 -1
  96. package/dist/tests/testHelper.d.ts +6 -12
  97. package/dist/tests.d.ts +1 -0
  98. package/dist/tests.js +3 -1
  99. package/dist/types/consentResponse.d.ts +8 -0
  100. package/dist/types/mcpAdmin.d.ts +58 -0
  101. package/dist/types/mcpAdmin.js +2 -0
  102. package/dist/types/mcpOAuth.d.ts +37 -2
  103. package/dist/types/mcpServiceToken.d.ts +2 -0
  104. package/e2e/smoke.ts +193 -0
  105. package/package.json +10 -5
  106. package/src/__snapshots__/openApi.test.ts.snap +288 -0
  107. package/src/__snapshots__/openApiBuilder.test.ts.snap +96 -0
  108. package/src/accountSecurity/accessActions.test.ts +723 -0
  109. package/src/accountSecurity/accessActions.ts +173 -0
  110. package/src/accountSecurity/accountSecurity.test.ts +947 -0
  111. package/src/accountSecurity/accountSecurityApp.ts +720 -0
  112. package/src/accountSecurity/accountSecurityService.ts +826 -0
  113. package/src/accountSecurity/credentialActions.test.ts +867 -0
  114. package/src/accountSecurity/credentialActions.ts +260 -0
  115. package/src/accountSecurity/membershipActions.ts +89 -0
  116. package/src/accountSecurity/orgSecurityRoutes.test.ts +841 -0
  117. package/src/accountSecurity/orgSecurityRoutes.ts +232 -0
  118. package/src/accountSecurity/securityEventHooks.ts +294 -0
  119. package/src/accountSecurity/securityEvents.ts +165 -0
  120. package/src/accountSecurity/securityNotifications.test.ts +1323 -0
  121. package/src/accountSecurity/securityNotifications.ts +516 -0
  122. package/src/adminModelRouter.test.ts +8 -6
  123. package/src/api.arrayOperations.test.ts +102 -22
  124. package/src/api.hooks.test.ts +12 -11
  125. package/src/api.query.test.ts +2 -2
  126. package/src/api.test.ts +8 -7
  127. package/src/api.ts +41 -10
  128. package/src/audit/auditApp.test.ts +1 -1
  129. package/src/audit/auditEventModel.ts +10 -7
  130. package/src/audit/cloudTasksEnqueue.test.ts +19 -14
  131. package/src/audit/processQueue.ts +4 -2
  132. package/src/audit/record.test.ts +15 -0
  133. package/src/audit/record.ts +10 -2
  134. package/src/auth.test.ts +21 -7
  135. package/src/authRecovery.test.ts +33 -10
  136. package/src/authRecovery.ts +34 -1
  137. package/src/authRecoveryBetterAuth.test.ts +169 -0
  138. package/src/authVerification.test.ts +7 -7
  139. package/src/betterAuth.ts +194 -8
  140. package/src/betterAuthApp.ts +32 -0
  141. package/src/betterAuthChallengeHeaders.test.ts +476 -0
  142. package/src/betterAuthChallengeHeaders.ts +227 -0
  143. package/src/betterAuthFeatures.test.ts +490 -0
  144. package/src/betterAuthFeatures.ts +283 -0
  145. package/src/betterAuthLinking.test.ts +846 -0
  146. package/src/betterAuthMethods.test.ts +138 -0
  147. package/src/betterAuthMethods.ts +98 -0
  148. package/src/betterAuthOAuthHandoff.test.ts +482 -69
  149. package/src/betterAuthOAuthHandoff.ts +293 -33
  150. package/src/betterAuthOAuthProxy.test.ts +421 -0
  151. package/src/betterAuthPasswordReset.test.ts +190 -0
  152. package/src/betterAuthSetPassword.test.ts +378 -0
  153. package/src/betterAuthSetPassword.ts +213 -0
  154. package/src/betterAuthSetup.test.ts +115 -57
  155. package/src/betterAuthSetup.ts +457 -38
  156. package/src/collectionRegistry.test.ts +4 -4
  157. package/src/consentApp.test.ts +869 -2
  158. package/src/consentApp.ts +438 -36
  159. package/src/consentStatus.test.ts +226 -0
  160. package/src/consentStatus.ts +171 -0
  161. package/src/errors.test.ts +81 -0
  162. package/src/errors.ts +50 -1
  163. package/src/expressServer.test.ts +29 -0
  164. package/src/expressServer.ts +3 -2
  165. package/src/frameworkModelNames.test.ts +8 -0
  166. package/src/frameworkModelNames.ts +4 -0
  167. package/src/githubAuth.test.ts +11 -11
  168. package/src/index.ts +38 -0
  169. package/src/isolated/migrateCliConnect.isolated.ts +3 -2
  170. package/src/mcp/actionTools.test.ts +11 -5
  171. package/src/mcp/adminTracking.test.ts +272 -0
  172. package/src/mcp/adminTracking.ts +104 -0
  173. package/src/mcp/auth.ts +18 -2
  174. package/src/mcp/oauth.test.ts +463 -2
  175. package/src/mcp/oauth.ts +184 -13
  176. package/src/mcp/oauthMetadata.ts +5 -2
  177. package/src/mcp/server.ts +67 -4
  178. package/src/mcp/serviceTokens.test.ts +2 -1
  179. package/src/mcp/toolGenerator.test.ts +9 -5
  180. package/src/migrations/cli.test.ts +15 -14
  181. package/src/migrations/cli.ts +1 -1
  182. package/src/migrations/generate.test.ts +2 -2
  183. package/src/migrations/load.test.ts +1 -1
  184. package/src/migrations/lock.test.ts +8 -3
  185. package/src/migrations/runner.test.ts +16 -5
  186. package/src/migrations/schemaCatalog.test.ts +4 -1
  187. package/src/models/consentResponse.ts +53 -0
  188. package/src/models/mcpOAuthClient.ts +100 -3
  189. package/src/models/mcpOAuthToken.test.ts +42 -0
  190. package/src/models/mcpOAuthToken.ts +62 -5
  191. package/src/models/mcpRequestLog.ts +81 -0
  192. package/src/models/mcpServiceToken.test.ts +23 -0
  193. package/src/models/mcpServiceToken.ts +10 -0
  194. package/src/models/mcpToolSetting.test.ts +69 -0
  195. package/src/models/mcpToolSetting.ts +138 -0
  196. package/src/models/versionConfig.ts +2 -0
  197. package/src/notifications/notificationsApp.test.ts +5 -8
  198. package/src/notifiers/slackWebApi.test.ts +30 -8
  199. package/src/openApi.test.ts +4 -4
  200. package/src/openApiValidator.test.ts +3 -3
  201. package/src/orgs/membershipGuards.ts +39 -0
  202. package/src/orgs/orgPermissions.test.ts +2 -2
  203. package/src/orgs/orgPlugin.test.ts +4 -3
  204. package/src/orgs/orgRbac.test.ts +1 -1
  205. package/src/orgs/orgSecurityDefects.test.ts +3 -1
  206. package/src/orgs/organizationSettings.test.ts +1 -1
  207. package/src/orgs/orgsApp.test.ts +104 -3
  208. package/src/orgs/orgsApp.ts +69 -28
  209. package/src/permissions.test.ts +2 -2
  210. package/src/rateLimit/policies.test.ts +53 -0
  211. package/src/rateLimit/policies.ts +8 -0
  212. package/src/rateLimit/redisStore.ioredis.test.ts +3 -2
  213. package/src/rbac/access.ts +4 -1
  214. package/src/rbac/assertAllowed.test.ts +1 -1
  215. package/src/rbac/auditModel.ts +10 -2
  216. package/src/rbac/realtimeAccess.test.ts +3 -2
  217. package/src/rbac/resolve.test.ts +65 -0
  218. package/src/rbac/resolve.ts +37 -17
  219. package/src/rbac/roleManager.test.ts +64 -0
  220. package/src/rbac/roleManager.ts +15 -6
  221. package/src/rbac/roleModel.test.ts +174 -1
  222. package/src/rbac/roleModel.ts +66 -3
  223. package/src/rbac/routes.test.ts +58 -0
  224. package/src/rbac/statements.test.ts +4 -1
  225. package/src/rbac/statements.ts +11 -1
  226. package/src/rbac/types.ts +6 -1
  227. package/src/rbac/userWriteGuards.test.ts +56 -5
  228. package/src/rbac/userWriteGuards.ts +5 -2
  229. package/src/realtime/realtime.test.ts +35 -31
  230. package/src/schemaMetadata.test.ts +39 -0
  231. package/src/schemaMetadata.ts +11 -1
  232. package/src/scrubAdminFields.test.ts +1 -1
  233. package/src/seedRunner.test.ts +56 -0
  234. package/src/seedRunner.ts +7 -2
  235. package/src/sync/adminWindowMutation.test.ts +4 -3
  236. package/src/sync/executors.test.ts +1 -1
  237. package/src/sync/scripts/compactTombstones.test.ts +4 -3
  238. package/src/sync/sync.test.ts +1 -1
  239. package/src/sync/syncPhaseC.test.ts +14 -11
  240. package/src/sync/syncRoutes.test.ts +8 -8
  241. package/src/sync/syncSeqPlugin.test.ts +1 -2
  242. package/src/sync/syncSocket.test.ts +5 -4
  243. package/src/terrenoApp.mcpServiceTokens.test.ts +2 -2
  244. package/src/terrenoApp.migrations.test.ts +8 -7
  245. package/src/terrenoApp.ts +34 -0
  246. package/src/tests/accountSecurityTestApp.ts +290 -0
  247. package/src/tests/betterAuthStubs.ts +189 -0
  248. package/src/tests/bunSetup.ts +1 -1
  249. package/src/tests/mockOidcProvider.ts +105 -0
  250. package/src/tests/models.ts +23 -0
  251. package/src/tests/softwareAuthenticator.ts +183 -0
  252. package/src/tests/testEnv.ts +7 -0
  253. package/src/tests.ts +1 -0
  254. package/src/types/consentResponse.ts +8 -0
  255. package/src/types/mcpAdmin.ts +80 -0
  256. package/src/types/mcpOAuth.ts +44 -3
  257. package/src/types/mcpServiceToken.ts +5 -0
  258. package/src/webhooks/verifiers/hmac.test.ts +1 -1
  259. package/tsconfig.typecheck.json +14 -0
@@ -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", () => {
@@ -42,6 +42,43 @@ const consentResponseSchema = new mongoose.Schema<ConsentResponseDocument, Conse
42
42
  required: true,
43
43
  type: String,
44
44
  },
45
+ provisional: {
46
+ default: false,
47
+ description:
48
+ "Whether another user recorded this agreement on the user's behalf. The user still sees the form and signs it themselves",
49
+ type: Boolean,
50
+ },
51
+ provisionalNote: {
52
+ description: "Required note from the provisional signer explaining how consent was obtained",
53
+ maxlength: 2000,
54
+ required: [
55
+ function (this: ConsentResponseDocument): boolean {
56
+ return this.provisional === true;
57
+ },
58
+ "provisionalNote is required for a provisional signature",
59
+ ],
60
+ trim: true,
61
+ type: String,
62
+ },
63
+ provisionalSignedBy: {
64
+ description: "The user who recorded this provisional signature",
65
+ ref: "User",
66
+ required: [
67
+ function (this: ConsentResponseDocument): boolean {
68
+ return this.provisional === true;
69
+ },
70
+ "provisionalSignedBy is required for a provisional signature",
71
+ ],
72
+ type: mongoose.Schema.Types.ObjectId,
73
+ },
74
+ provisionalSignerIp: {
75
+ description: "IP address of the provisional signer, captured for audit purposes",
76
+ type: String,
77
+ },
78
+ provisionalSignerUserAgent: {
79
+ description: "User-agent string of the provisional signer's browser or app",
80
+ type: String,
81
+ },
45
82
  signature: {
46
83
  description: "Base64-encoded signature image or typed signature text, if captured",
47
84
  type: String,
@@ -61,6 +98,22 @@ const consentResponseSchema = new mongoose.Schema<ConsentResponseDocument, Conse
61
98
  required: true,
62
99
  type: mongoose.Schema.Types.ObjectId,
63
100
  },
101
+ voidedAt: {
102
+ description:
103
+ "When a provisional signature was voided. Voided signatures no longer count as consent",
104
+ type: Date,
105
+ },
106
+ voidedBy: {
107
+ description: "The user who voided this provisional signature",
108
+ ref: "User",
109
+ type: mongoose.Schema.Types.ObjectId,
110
+ },
111
+ voidReason: {
112
+ description: "Why the provisional signature was voided",
113
+ maxlength: 2000,
114
+ trim: true,
115
+ type: String,
116
+ },
64
117
  },
65
118
  {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
66
119
  );
@@ -1,12 +1,19 @@
1
+ import {randomUUID} from "node:crypto";
2
+ import {DateTime} from "luxon";
1
3
  import mongoose from "mongoose";
2
4
 
3
5
  import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
- import type {McpOAuthClientDocument, McpOAuthClientModel} from "../types/mcpOAuth";
6
+ import type {
7
+ McpOAuthClientDocument,
8
+ McpOAuthClientModel,
9
+ McpOAuthConfidentialClientOptions,
10
+ } from "../types/mcpOAuth";
11
+ import {generateMcpOAuthSecret, hashMcpOAuthSecret, McpOAuthToken} from "./mcpOAuthToken";
5
12
 
6
13
  const mcpOAuthClientSchema = new mongoose.Schema<McpOAuthClientDocument, McpOAuthClientModel>(
7
14
  {
8
15
  clientId: {
9
- description: "Public OAuth client identifier issued by dynamic client registration",
16
+ description: "Public OAuth client identifier",
10
17
  required: true,
11
18
  type: String,
12
19
  unique: true,
@@ -16,22 +23,42 @@ const mcpOAuthClientSchema = new mongoose.Schema<McpOAuthClientDocument, McpOAut
16
23
  trim: true,
17
24
  type: String,
18
25
  },
26
+ clientSecretHash: {
27
+ description: "SHA-256 hash of the confidential client secret. Unset for public clients",
28
+ type: String,
29
+ },
19
30
  grantTypes: {
20
31
  description: "OAuth grant types the client may use",
21
32
  type: [String],
22
33
  },
23
34
  redirectUris: {
24
- description: "Exact redirect URIs the client registered",
35
+ description:
36
+ "Registered redirect URIs. Loopback hosts (localhost, 127.0.0.1, [::1]) match any port; every other URI must match exactly",
25
37
  type: [String],
26
38
  },
27
39
  responseTypes: {
28
40
  description: "OAuth response types the client may request",
29
41
  type: [String],
30
42
  },
43
+ revokedAt: {
44
+ description: "When the client was revoked. A revoked client cannot take new grants",
45
+ type: Date,
46
+ },
31
47
  scope: {
32
48
  description: "Space-separated scopes the client registered for",
33
49
  type: String,
34
50
  },
51
+ tokenEndpointAuthMethod: {
52
+ description:
53
+ "How the client authenticates at the token endpoint. none is a public client; client_secret_basic and client_secret_post are confidential",
54
+ enum: ["none", "client_secret_basic", "client_secret_post"],
55
+ type: String,
56
+ },
57
+ userId: {
58
+ description: "User a client_credentials token acts as",
59
+ ref: "User",
60
+ type: mongoose.Schema.Types.ObjectId,
61
+ },
35
62
  },
36
63
  {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
37
64
  );
@@ -40,6 +67,76 @@ mcpOAuthClientSchema.plugin(createdUpdatedPlugin);
40
67
  mcpOAuthClientSchema.plugin(findOneOrNone);
41
68
  mcpOAuthClientSchema.plugin(findExactlyOne);
42
69
 
70
+ const revokeTokensForClient = async (clientId: string | undefined): Promise<void> => {
71
+ if (!clientId) {
72
+ return;
73
+ }
74
+ await McpOAuthToken.revokeClient(clientId);
75
+ };
76
+
77
+ mcpOAuthClientSchema.pre("deleteOne", {document: true, query: false}, async function () {
78
+ await revokeTokensForClient(this.clientId);
79
+ });
80
+
81
+ mcpOAuthClientSchema.pre("deleteOne", {document: false, query: true}, async function () {
82
+ // deleteOne removes one document. Pin that document so its tokens are the ones revoked.
83
+ const [existing] = await this.model.find(this.getFilter()).limit(1).select({_id: 1, clientId: 1});
84
+ if (!existing) {
85
+ return;
86
+ }
87
+ this.setQuery({_id: existing._id});
88
+ await revokeTokensForClient(existing.clientId);
89
+ });
90
+
91
+ mcpOAuthClientSchema.pre("findOneAndDelete", async function () {
92
+ const [existing] = await this.model.find(this.getFilter()).limit(1).select({_id: 1, clientId: 1});
93
+ if (!existing) {
94
+ return;
95
+ }
96
+ this.setQuery({_id: existing._id});
97
+ await revokeTokensForClient(existing.clientId);
98
+ });
99
+
100
+ mcpOAuthClientSchema.pre("deleteMany", async function () {
101
+ const clients = await this.model.find(this.getFilter()).select({clientId: 1});
102
+ for (const client of clients) {
103
+ await revokeTokensForClient(client.clientId);
104
+ }
105
+ });
106
+
107
+ mcpOAuthClientSchema.statics = {
108
+ ...mcpOAuthClientSchema.statics,
109
+ async issueConfidential(
110
+ this: McpOAuthClientModel,
111
+ options: McpOAuthConfidentialClientOptions
112
+ ): Promise<{client: McpOAuthClientDocument; clientSecret: string}> {
113
+ const clientSecret = generateMcpOAuthSecret("mcpcs_");
114
+ const client = await this.create({
115
+ clientId: options.clientId ?? randomUUID(),
116
+ clientName: options.clientName,
117
+ clientSecretHash: hashMcpOAuthSecret(clientSecret),
118
+ grantTypes: ["client_credentials"],
119
+ redirectUris: [],
120
+ responseTypes: [],
121
+ scope: options.scope,
122
+ tokenEndpointAuthMethod: options.tokenEndpointAuthMethod,
123
+ userId: new mongoose.Types.ObjectId(String(options.userId)),
124
+ });
125
+ return {client, clientSecret};
126
+ },
127
+ async revoke(
128
+ this: McpOAuthClientModel,
129
+ clientId: string
130
+ ): Promise<McpOAuthClientDocument | null> {
131
+ await this.updateOne(
132
+ {clientId, revokedAt: {$exists: false}},
133
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
134
+ );
135
+ await McpOAuthToken.revokeClient(clientId);
136
+ return this.findOneOrNone({clientId});
137
+ },
138
+ };
139
+
43
140
  export const McpOAuthClient =
44
141
  (mongoose.models.TerrenoMcpOAuthClient as McpOAuthClientModel | undefined) ??
45
142
  mongoose.model<McpOAuthClientDocument, McpOAuthClientModel>(
@@ -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
+ });
@@ -62,6 +62,11 @@ const mcpOAuthTokenSchema = new mongoose.Schema<McpOAuthTokenDocument, McpOAuthT
62
62
  required: true,
63
63
  type: String,
64
64
  },
65
+ hasRefreshToken: {
66
+ description:
67
+ "False when this document is an access-only client_credentials token. The refresh hash is then of a discarded secret and cannot be exchanged",
68
+ type: Boolean,
69
+ },
65
70
  refreshExpiresAt: {
66
71
  description: "When the refresh token stops being exchangeable; the document is removed then",
67
72
  required: true,
@@ -116,21 +121,30 @@ mcpOAuthTokenSchema.statics = {
116
121
  async issue(
117
122
  this: McpOAuthTokenModel,
118
123
  options: McpOAuthTokenIssueOptions
119
- ): Promise<{accessToken: string; mcpOAuthToken: McpOAuthTokenDocument; refreshToken: string}> {
124
+ ): Promise<{accessToken: string; mcpOAuthToken: McpOAuthTokenDocument; refreshToken?: string}> {
120
125
  const familyId = options.familyId ?? randomUUID();
121
126
  if (await isFamilyRevoked(familyId)) {
122
127
  throw new McpOAuthFamilyRevokedError(familyId);
123
128
  }
129
+ const includeRefreshToken = options.includeRefreshToken !== false;
124
130
  const accessToken = generateMcpOAuthSecret(MCP_OAUTH_ACCESS_TOKEN_PREFIX);
125
- const refreshToken = generateMcpOAuthSecret(MCP_OAUTH_REFRESH_TOKEN_PREFIX);
131
+ // Access-only grants still store a unique hash so the refreshTokenHash index stays unique.
132
+ // The preimage is discarded, and hasRefreshToken false makes it unusable for refresh.
133
+ const refreshSecret = includeRefreshToken
134
+ ? generateMcpOAuthSecret(MCP_OAUTH_REFRESH_TOKEN_PREFIX)
135
+ : generateMcpOAuthSecret("discarded_");
126
136
  const now = DateTime.now();
137
+ const refreshTtlSeconds = includeRefreshToken
138
+ ? options.refreshTokenTtlSeconds
139
+ : options.accessTokenTtlSeconds;
127
140
  const mcpOAuthToken = await this.create({
128
141
  accessExpiresAt: now.plus({seconds: options.accessTokenTtlSeconds}).toJSDate(),
129
142
  accessTokenHash: hashMcpOAuthSecret(accessToken),
130
143
  clientId: options.clientId,
131
144
  familyId,
132
- refreshExpiresAt: now.plus({seconds: options.refreshTokenTtlSeconds}).toJSDate(),
133
- refreshTokenHash: hashMcpOAuthSecret(refreshToken),
145
+ hasRefreshToken: includeRefreshToken,
146
+ refreshExpiresAt: now.plus({seconds: refreshTtlSeconds}).toJSDate(),
147
+ refreshTokenHash: hashMcpOAuthSecret(refreshSecret),
134
148
  resource: options.resource,
135
149
  scope: options.scope,
136
150
  tokenEpoch: options.tokenEpoch ?? 0,
@@ -145,7 +159,32 @@ mcpOAuthTokenSchema.statics = {
145
159
  );
146
160
  throw new McpOAuthFamilyRevokedError(familyId);
147
161
  }
148
- return {accessToken, mcpOAuthToken, refreshToken};
162
+ return {
163
+ accessToken,
164
+ mcpOAuthToken,
165
+ refreshToken: includeRefreshToken ? refreshSecret : undefined,
166
+ };
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
+ },
182
+ async revokeClient(this: McpOAuthTokenModel, clientId: string): Promise<void> {
183
+ const tokens = await this.find({clientId, revokedAt: {$exists: false}}).select({familyId: 1});
184
+ const familyIds = new Set(tokens.map((token) => token.familyId));
185
+ for (const familyId of familyIds) {
186
+ await this.revokeFamily(familyId);
187
+ }
149
188
  },
150
189
  async revokeFamily(this: McpOAuthTokenModel, familyId: string): Promise<void> {
151
190
  const now = DateTime.now();
@@ -186,6 +225,24 @@ mcpOAuthTokenSchema.statics = {
186
225
  },
187
226
  };
188
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
+
189
246
  export const McpOAuthToken =
190
247
  (mongoose.models.TerrenoMcpOAuthToken as McpOAuthTokenModel | undefined) ??
191
248
  mongoose.model<McpOAuthTokenDocument, McpOAuthTokenModel>(
@@ -0,0 +1,81 @@
1
+ import mongoose from "mongoose";
2
+
3
+ import {createdUpdatedPlugin, findExactlyOne, findOneOrNone} from "../plugins";
4
+ import type {McpRequestLogDocument, McpRequestLogModel} from "../types/mcpAdmin";
5
+
6
+ /**
7
+ * One row per MCP tool call when `mcpRequestLog` is on. Metadata only: tool arguments, results,
8
+ * and error messages are never stored. Rows expire at `expiresAt`.
9
+ */
10
+ const mcpRequestLogSchema = new mongoose.Schema<McpRequestLogDocument, McpRequestLogModel>(
11
+ {
12
+ credential: {
13
+ description: "Credential type that authenticated the call",
14
+ enum: ["jwt", "better-auth-session", "mcp-service-token", "oauth"],
15
+ type: String,
16
+ },
17
+ durationMs: {
18
+ description: "Time the tool handler took, in milliseconds",
19
+ required: true,
20
+ type: Number,
21
+ },
22
+ errorName: {
23
+ description: "Error class name when the tool threw; never the error message",
24
+ type: String,
25
+ },
26
+ expiresAt: {
27
+ description: "When this log row is removed",
28
+ required: true,
29
+ type: Date,
30
+ },
31
+ oauthClientId: {
32
+ description: "OAuth client id when the call used an MCP OAuth access token",
33
+ index: true,
34
+ type: String,
35
+ },
36
+ oauthFamilyId: {
37
+ description: "OAuth token family (one approved connection) when the call used OAuth",
38
+ type: String,
39
+ },
40
+ outcome: {
41
+ description: "ok, tool_error (the tool returned isError), or exception (the tool threw)",
42
+ enum: ["ok", "tool_error", "exception"],
43
+ required: true,
44
+ type: String,
45
+ },
46
+ serviceTokenId: {
47
+ description: "Service token used for the call, when the credential was a service token",
48
+ index: true,
49
+ ref: "TerrenoMcpServiceToken",
50
+ type: mongoose.Schema.Types.ObjectId,
51
+ },
52
+ toolName: {
53
+ description: "Name of the MCP tool that was called",
54
+ index: true,
55
+ required: true,
56
+ type: String,
57
+ },
58
+ userId: {
59
+ description: "User the call acted as",
60
+ index: true,
61
+ ref: "User",
62
+ type: mongoose.Schema.Types.ObjectId,
63
+ },
64
+ },
65
+ {strict: "throw", toJSON: {virtuals: true}, toObject: {virtuals: true}}
66
+ );
67
+
68
+ mcpRequestLogSchema.index({expiresAt: 1}, {expireAfterSeconds: 0});
69
+ mcpRequestLogSchema.index({created: -1});
70
+
71
+ mcpRequestLogSchema.plugin(createdUpdatedPlugin);
72
+ mcpRequestLogSchema.plugin(findOneOrNone);
73
+ mcpRequestLogSchema.plugin(findExactlyOne);
74
+
75
+ export const McpRequestLog =
76
+ (mongoose.models.TerrenoMcpRequestLog as McpRequestLogModel | undefined) ??
77
+ mongoose.model<McpRequestLogDocument, McpRequestLogModel>(
78
+ "TerrenoMcpRequestLog",
79
+ mcpRequestLogSchema,
80
+ "mcprequestlogs"
81
+ );
@@ -127,3 +127,26 @@ describe("McpServiceToken", () => {
127
127
  assert.isNull(await McpServiceToken.verify(issued.token));
128
128
  });
129
129
  });
130
+
131
+ describe("McpServiceToken.revokeAllForUser", () => {
132
+ beforeEach(async () => {
133
+ await McpServiceToken.deleteMany({});
134
+ });
135
+
136
+ it("revokes only that user's active tokens", async () => {
137
+ const userId = new mongoose.Types.ObjectId();
138
+ const otherId = new mongoose.Types.ObjectId();
139
+ await McpServiceToken.issueFor({_id: userId}, {name: "A"});
140
+ await McpServiceToken.issueFor({_id: userId}, {name: "B"});
141
+ await McpServiceToken.issueFor({_id: otherId}, {name: "Other"});
142
+
143
+ const revoked = await McpServiceToken.revokeAllForUser(userId);
144
+
145
+ assert.equal(revoked, 2);
146
+ assert.equal(await McpServiceToken.countDocuments({revokedAt: {$exists: false}, userId}), 0);
147
+ assert.equal(
148
+ await McpServiceToken.countDocuments({revokedAt: {$exists: false}, userId: otherId}),
149
+ 1
150
+ );
151
+ });
152
+ });
@@ -131,6 +131,16 @@ mcpServiceTokenSchema.statics = {
131
131
  });
132
132
  return {mcpServiceToken, token};
133
133
  },
134
+ async revokeAllForUser(
135
+ this: McpServiceTokenModel,
136
+ userId: mongoose.Types.ObjectId | string
137
+ ): Promise<number> {
138
+ const result = await this.updateMany(
139
+ {revokedAt: {$exists: false}, userId: new mongoose.Types.ObjectId(String(userId))},
140
+ {$set: {revokedAt: DateTime.now().toJSDate()}}
141
+ );
142
+ return result.modifiedCount;
143
+ },
134
144
  async revokeForUser(
135
145
  this: McpServiceTokenModel,
136
146
  user: {_id: {toString(): string}},
@@ -0,0 +1,69 @@
1
+ import {afterEach, beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import {DateTime} from "luxon";
3
+
4
+ import {setupDb} from "../tests";
5
+ import {McpToolSetting} from "./mcpToolSetting";
6
+
7
+ describe("McpToolSetting.disabledNames", () => {
8
+ const restores: Array<() => void> = [];
9
+
10
+ beforeEach(async () => {
11
+ await setupDb();
12
+ await McpToolSetting.deleteMany({});
13
+ });
14
+
15
+ afterEach(() => {
16
+ for (const restore of restores.splice(0)) {
17
+ restore();
18
+ }
19
+ });
20
+
21
+ it("reuses the cached set until a write through the model clears it", async () => {
22
+ await McpToolSetting.create({enabled: false, name: "a", source: "custom"});
23
+ expect([...(await McpToolSetting.disabledNames())]).toEqual(["a"]);
24
+
25
+ // A write that bypasses the model's hooks is not seen until the cache expires.
26
+ await McpToolSetting.collection.updateOne({name: "a"}, {$set: {enabled: true}});
27
+ expect([...(await McpToolSetting.disabledNames())]).toEqual(["a"]);
28
+
29
+ await McpToolSetting.updateOne({name: "a"}, {$set: {enabled: false}});
30
+ await McpToolSetting.collection.updateOne({name: "a"}, {$set: {enabled: true}});
31
+ await McpToolSetting.updateOne({name: "b"}, {$set: {enabled: false}});
32
+ expect([...(await McpToolSetting.disabledNames())]).toEqual([]);
33
+ });
34
+
35
+ it("reads again after the TTL", async () => {
36
+ await McpToolSetting.create({enabled: false, name: "a", source: "custom"});
37
+ expect((await McpToolSetting.disabledNames()).size).toBe(1);
38
+ await McpToolSetting.collection.updateOne({name: "a"}, {$set: {enabled: true}});
39
+
40
+ const later = DateTime.now().plus({seconds: 10});
41
+ const now = spyOn(DateTime, "now").mockReturnValue(later);
42
+ restores.push(() => now.mockRestore());
43
+
44
+ expect((await McpToolSetting.disabledNames()).size).toBe(0);
45
+ });
46
+
47
+ it("keeps the last known switches when a read fails, and fails closed with none", async () => {
48
+ await McpToolSetting.create({enabled: false, name: "a", source: "custom"});
49
+ expect((await McpToolSetting.disabledNames()).size).toBe(1);
50
+
51
+ const later = DateTime.now().plus({seconds: 10});
52
+ const now = spyOn(DateTime, "now").mockReturnValue(later);
53
+ restores.push(() => now.mockRestore());
54
+ const find = spyOn(McpToolSetting, "find").mockImplementation(() => {
55
+ throw new Error("mongo down");
56
+ });
57
+ restores.push(() => find.mockRestore());
58
+
59
+ expect([...(await McpToolSetting.disabledNames())]).toEqual(["a"]);
60
+
61
+ find.mockRestore();
62
+ await McpToolSetting.deleteMany({});
63
+ const failing = spyOn(McpToolSetting, "find").mockImplementation(() => {
64
+ throw new Error("mongo down");
65
+ });
66
+ restores.push(() => failing.mockRestore());
67
+ await expect(McpToolSetting.disabledNames()).rejects.toThrow("mongo down");
68
+ });
69
+ });