@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
@@ -314,7 +314,7 @@ const invokeGitHubVerify = (
314
314
  if (!strategy) {
315
315
  throw new Error("github strategy not registered");
316
316
  }
317
- return new Promise<{err: VerifyError | null; user: VerifiedUser}>((resolve) => {
317
+ return new Promise<{err: VerifyError | null; user?: VerifiedUser}>((resolve) => {
318
318
  const done = (err: VerifyError | null, user?: VerifiedUser) => resolve({err, user});
319
319
  strategy._verify(req, accessToken, refreshToken, profile, done);
320
320
  });
@@ -399,9 +399,9 @@ describe("GitHub strategy verify callback", () => {
399
399
  const result = await invokeGitHubVerify({}, "access", "refresh", profile);
400
400
  expect(result.err).toBeNull();
401
401
  expect(result.user).toBeDefined();
402
- expect(result.user.githubId).toBe("gh-new-1");
403
- expect(result.user.githubUsername).toBe("newghuser");
404
- expect(result.user.email).toBe("new@example.com");
402
+ expect(result.user?.githubId).toBe("gh-new-1");
403
+ expect(result.user?.githubUsername).toBe("newghuser");
404
+ expect(result.user?.email).toBe("new@example.com");
405
405
  });
406
406
 
407
407
  it("logs in existing GitHub user", async () => {
@@ -423,7 +423,7 @@ describe("GitHub strategy verify callback", () => {
423
423
  username: "ghuser",
424
424
  });
425
425
  expect(result.err).toBeNull();
426
- expect(result.user._id.toString()).toBe(existingUser._id.toString());
426
+ expect(result.user?._id.toString()).toBe(existingUser._id.toString());
427
427
  });
428
428
 
429
429
  it("links GitHub to authenticated user when allowAccountLinking=true", async () => {
@@ -447,9 +447,9 @@ describe("GitHub strategy verify callback", () => {
447
447
  username: "linkedghuser",
448
448
  });
449
449
  expect(result.err).toBeNull();
450
- expect(result.user._id.toString()).toBe(existingUser._id.toString());
451
- expect(result.user.githubId).toBe("gh-link-1");
452
- expect(result.user.githubUsername).toBe("linkedghuser");
450
+ expect(result.user?._id.toString()).toBe(existingUser._id.toString());
451
+ expect(result.user?.githubId).toBe("gh-link-1");
452
+ expect(result.user?.githubUsername).toBe("linkedghuser");
453
453
  });
454
454
 
455
455
  it("does not treat an ambient req.user as a link target", async () => {
@@ -467,7 +467,7 @@ describe("GitHub strategy verify callback", () => {
467
467
  id: "gh-ambient-1",
468
468
  });
469
469
  expect(result.err).toBeNull();
470
- expect(result.user._id.toString()).not.toBe(ambientUser._id.toString());
470
+ expect(result.user?._id.toString()).not.toBe(ambientUser._id.toString());
471
471
  const ambientRow = await GitHubTestUserModel.findById(ambientUser._id);
472
472
  expect(ambientRow?.githubId).toBeUndefined();
473
473
  });
@@ -547,8 +547,8 @@ describe("GitHub strategy verify callback", () => {
547
547
  username: "emailuserghuser",
548
548
  });
549
549
  expect(result.err).toBeNull();
550
- expect(result.user.githubId).toBe("gh-email-link-1");
551
- expect(result.user.email).toBe("emailuser@example.com");
550
+ expect(result.user?.githubId).toBe("gh-email-link-1");
551
+ expect(result.user?.email).toBe("emailuser@example.com");
552
552
  });
553
553
 
554
554
  it("rejects email-link when allowAccountLinking=false", async () => {
package/src/index.ts CHANGED
@@ -1,8 +1,24 @@
1
+ export {ISSUE_SIGN_IN_LINK_PERMISSION} from "./accountSecurity/accessActions";
2
+ export * from "./accountSecurity/accountSecurityApp";
3
+ export * from "./accountSecurity/accountSecurityService";
4
+ export {suspendMembershipAction} from "./accountSecurity/membershipActions";
5
+ export {
6
+ createOrgSecurityAuthorizer,
7
+ mountOrgSecurityRoutes,
8
+ type OrgRecoveryOptions,
9
+ } from "./accountSecurity/orgSecurityRoutes";
10
+ export {
11
+ createSecurityEventsPlugin,
12
+ recordSelfSecurityAction,
13
+ } from "./accountSecurity/securityEventHooks";
14
+ export * from "./accountSecurity/securityEvents";
15
+ export * from "./accountSecurity/securityNotifications";
1
16
  export * from "./actions";
2
17
  export * from "./adminTypes";
3
18
  export * from "./api";
4
19
  export {AuditApp, type AuditAppOptions} from "./audit/auditApp";
5
20
  export {
21
+ AUDIT_EVENT_SOURCES,
6
22
  type AuditEventDocument,
7
23
  type AuditEventModel,
8
24
  type AuditEventOperation,
@@ -35,12 +51,24 @@ export * from "./authRecovery";
35
51
  export * from "./authTokens";
36
52
  export * from "./betterAuth";
37
53
  export * from "./betterAuthApp";
54
+ export * from "./betterAuthChallengeHeaders";
55
+ export * from "./betterAuthFeatures";
56
+ export * from "./betterAuthMethods";
38
57
  export * from "./betterAuthSetup";
39
58
  export * from "./browserLogsRoute";
40
59
  export * from "./config";
41
60
  export * from "./configurationApp";
42
61
  export * from "./configurationPlugin";
43
62
  export * from "./consentApp";
63
+ export {
64
+ type ConsentStatus,
65
+ type ConsentStatusForm,
66
+ type ConsentStatusProvisional,
67
+ type ConsentStatusRow,
68
+ type ConsentStatusSigner,
69
+ getConsentStatuses,
70
+ type ResolveConsentForms,
71
+ } from "./consentStatus";
44
72
  export * from "./envConfigurationPlugin";
45
73
  export * from "./errors";
46
74
  export * from "./expressServer";
@@ -53,6 +81,11 @@ export {
53
81
  export * from "./githubAuth";
54
82
  export * from "./httpClient";
55
83
  export * from "./logger";
84
+ export {
85
+ type McpRequestLogAppOption,
86
+ type ResolvedMcpRequestLogOptions,
87
+ resolveMcpRequestLogOption,
88
+ } from "./mcp/adminTracking";
56
89
  export {
57
90
  extractAuthFromHeaders,
58
91
  extractUserFromHeaders,
@@ -113,7 +146,9 @@ export {McpOAuthAuthorization} from "./models/mcpOAuthAuthorization";
113
146
  export {McpOAuthClient} from "./models/mcpOAuthClient";
114
147
  export {McpOAuthRevokedFamily} from "./models/mcpOAuthRevokedFamily";
115
148
  export {McpOAuthFamilyRevokedError, McpOAuthToken} from "./models/mcpOAuthToken";
149
+ export {McpRequestLog} from "./models/mcpRequestLog";
116
150
  export * from "./models/mcpServiceToken";
151
+ export {McpToolSetting} from "./models/mcpToolSetting";
117
152
  export * from "./models/notification";
118
153
  export * from "./models/notificationPreference";
119
154
  export * from "./models/versionConfig";
@@ -319,12 +354,15 @@ export * from "./terrenoPlugin";
319
354
  export * from "./transformers";
320
355
  export * from "./types/consentForm";
321
356
  export * from "./types/consentResponse";
357
+ export type * from "./types/mcpAdmin";
322
358
  export type {
323
359
  McpOAuthAuthorizationDocument,
324
360
  McpOAuthAuthorizationStatus,
325
361
  McpOAuthClientDocument,
362
+ McpOAuthConfidentialClientOptions,
326
363
  McpOAuthRevokedFamilyDocument,
327
364
  McpOAuthTokenDocument,
365
+ McpOAuthTokenEndpointAuthMethod,
328
366
  } from "./types/mcpOAuth";
329
367
  export * from "./utils";
330
368
  export * from "./versionCheckPlugin";
@@ -9,9 +9,10 @@ import {assert} from "chai";
9
9
  import mongoose from "mongoose";
10
10
  import {runMigrateCli} from "../migrations/cli";
11
11
  import {setupDb} from "../tests";
12
+ import {partialEnv} from "../tests/testEnv";
12
13
 
13
14
  const fixtures = (...parts: string[]): string => {
14
- return join(import.meta.dir, "..", "migrations", "fixtures", ...parts);
15
+ return join(__dirname, "..", "migrations", "fixtures", ...parts);
15
16
  };
16
17
 
17
18
  describe("runMigrateCli Mongo URI connect", () => {
@@ -27,7 +28,7 @@ describe("runMigrateCli Mongo URI connect", () => {
27
28
  const err: string[] = [];
28
29
  const code = await runMigrateCli({
29
30
  argv: ["status", "--dir", fixtures("valid")],
30
- env: {MONGODB_URI: uri, NODE_ENV: "test"},
31
+ env: partialEnv({MONGODB_URI: uri, NODE_ENV: "test"}),
31
32
  stderr: {
32
33
  write: (chunk: string): void => {
33
34
  err.push(chunk);
@@ -57,7 +57,9 @@ const widgetRouter = (extra: Record<string, unknown> = {}) =>
57
57
  collectionActions: {
58
58
  countMine: {
59
59
  handler: async ({req, user}) => ({
60
- count: await WidgetModel.countDocuments({ownerId: user?._id}),
60
+ count: await WidgetModel.countDocuments({
61
+ ownerId: user?._id as mongoose.Types.ObjectId | undefined,
62
+ }),
61
63
  credential: getCurrentRequestContext()?.credential ?? null,
62
64
  isMCPRequest: (req as unknown as {isMCPRequest?: boolean}).isMCPRequest ?? false,
63
65
  }),
@@ -67,7 +69,7 @@ const widgetRouter = (extra: Record<string, unknown> = {}) =>
67
69
  },
68
70
  echoId: {
69
71
  body: z.object({id: z.string()}).strict(),
70
- handler: async ({body}) => ({id: body.id}),
72
+ handler: async ({body}) => ({id: (body as {id: string}).id}),
71
73
  mcp: {name: "widgets_echo_id"},
72
74
  method: "POST",
73
75
  permissions: [Permissions.IsAuthenticated],
@@ -84,7 +86,10 @@ const widgetRouter = (extra: Record<string, unknown> = {}) =>
84
86
  },
85
87
  instanceActions: {
86
88
  peek: {
87
- handler: async ({doc, query}) => ({name: doc.name, verbose: query.verbose}),
89
+ handler: async ({doc, query}) => ({
90
+ name: doc.name,
91
+ verbose: (query as {verbose?: boolean}).verbose,
92
+ }),
88
93
  mcp: {name: "widgets_peek"},
89
94
  method: "GET",
90
95
  permissions: [Permissions.IsAuthenticated],
@@ -94,10 +99,11 @@ const widgetRouter = (extra: Record<string, unknown> = {}) =>
94
99
  body: z.object({amount: z.number().int().min(1)}).strict(),
95
100
  description: "Add stars to a widget",
96
101
  handler: async ({body, doc, req}) => {
97
- await WidgetModel.updateOne({_id: doc._id}, {$inc: {stars: body.amount}});
102
+ const {amount} = body as {amount: number};
103
+ await WidgetModel.updateOne({_id: doc._id}, {$inc: {stars: amount}});
98
104
  return {
99
105
  isMCPRequest: (req as unknown as {isMCPRequest?: boolean}).isMCPRequest ?? false,
100
- stars: doc.stars + body.amount,
106
+ stars: doc.stars + amount,
101
107
  };
102
108
  },
103
109
  mcp: {name: "widgets_star"},
@@ -0,0 +1,272 @@
1
+ import {beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import express from "express";
3
+ import mongoose from "mongoose";
4
+ import supertest from "supertest";
5
+ import {z} from "zod";
6
+
7
+ import type {UserModel as AuthUserModel} from "../auth";
8
+ import {logger} from "../logger";
9
+ import {McpRequestLog} from "../models/mcpRequestLog";
10
+ import {McpServiceToken} from "../models/mcpServiceToken";
11
+ import {McpToolSetting} from "../models/mcpToolSetting";
12
+ import {TerrenoApp} from "../terrenoApp";
13
+ import {setupDb, UserModel} from "../tests";
14
+ import type {McpRequestLogOutcome} from "../types/mcpAdmin";
15
+ import {recordMcpToolCall, resolveMcpRequestLogOption} from "./adminTracking";
16
+ import {clearMCPRegistry, registerMCPTool} from "./registry";
17
+ import {mountMCPServer} from "./server";
18
+
19
+ const ACCEPT = "application/json, text/event-stream";
20
+
21
+ const registerTools = (): void => {
22
+ registerMCPTool({
23
+ description: "Echo a secret message",
24
+ handler: async (args) => {
25
+ return {content: [{text: `echo ${String(args.message)}`, type: "text"}]};
26
+ },
27
+ name: "echo_message",
28
+ zodSchema: z.object({message: z.string()}).strict(),
29
+ });
30
+ registerMCPTool({
31
+ description: "Always fails",
32
+ handler: async () => {
33
+ throw new TypeError("patient 123 not found");
34
+ },
35
+ name: "always_throws",
36
+ zodSchema: z.object({}).strict(),
37
+ });
38
+ };
39
+
40
+ const buildApp = (options: {requestLog?: boolean; toolSettings?: boolean}): express.Application => {
41
+ const app = express();
42
+ app.use(express.json());
43
+ mountMCPServer(app, {
44
+ mcpServiceTokens: true,
45
+ requestLog: options.requestLog ? {retentionDays: 7} : undefined,
46
+ toolSettings: options.toolSettings,
47
+ userModel: UserModel as unknown as AuthUserModel,
48
+ });
49
+ return app;
50
+ };
51
+
52
+ const callTool = (
53
+ app: express.Application,
54
+ name: string,
55
+ args: Record<string, unknown>,
56
+ token?: string
57
+ ): supertest.Test => {
58
+ const request = supertest(app).post("/mcp").set("accept", ACCEPT);
59
+ if (token) {
60
+ request.set("authorization", `Bearer ${token}`);
61
+ }
62
+ return request.send({
63
+ id: 1,
64
+ jsonrpc: "2.0",
65
+ method: "tools/call",
66
+ params: {arguments: args, name},
67
+ });
68
+ };
69
+
70
+ const listTools = (app: express.Application): supertest.Test =>
71
+ supertest(app)
72
+ .post("/mcp")
73
+ .set("accept", ACCEPT)
74
+ .send({id: 2, jsonrpc: "2.0", method: "tools/list", params: {}});
75
+
76
+ // Request-log writes are fire-and-forget, so poll briefly for the row.
77
+ const waitForLogs = async (count: number): Promise<void> => {
78
+ for (let attempt = 0; attempt < 50; attempt++) {
79
+ if ((await McpRequestLog.countDocuments({})) >= count) {
80
+ return;
81
+ }
82
+ await new Promise((resolve) => setTimeout(resolve, 10));
83
+ }
84
+ };
85
+
86
+ const waitForSettings = async (count: number): Promise<void> => {
87
+ for (let attempt = 0; attempt < 50; attempt++) {
88
+ if ((await McpToolSetting.countDocuments({})) >= count) {
89
+ return;
90
+ }
91
+ await new Promise((resolve) => setTimeout(resolve, 10));
92
+ }
93
+ };
94
+
95
+ describe("resolveMcpRequestLogOption", () => {
96
+ it("is off unless enabled", () => {
97
+ expect(resolveMcpRequestLogOption(undefined)).toBeUndefined();
98
+ expect(resolveMcpRequestLogOption(false)).toBeUndefined();
99
+ expect(resolveMcpRequestLogOption({enabled: false})).toBeUndefined();
100
+ });
101
+
102
+ it("defaults retention to 30 days", () => {
103
+ expect(resolveMcpRequestLogOption(true)).toEqual({retentionDays: 30});
104
+ expect(resolveMcpRequestLogOption({enabled: true, retentionDays: 3})).toEqual({
105
+ retentionDays: 3,
106
+ });
107
+ });
108
+
109
+ it("rejects a non-positive retention", () => {
110
+ expect(() => resolveMcpRequestLogOption({enabled: true, retentionDays: 0})).toThrow();
111
+ });
112
+ });
113
+
114
+ describe("MCP request log", () => {
115
+ let notAdmin: {_id: mongoose.Types.ObjectId};
116
+ beforeEach(async () => {
117
+ clearMCPRegistry();
118
+ registerTools();
119
+ const users = await setupDb();
120
+ notAdmin = users[1];
121
+ await McpRequestLog.deleteMany({});
122
+ await McpServiceToken.deleteMany({});
123
+ });
124
+
125
+ it("records the tool, user, and service token but never the arguments or result", async () => {
126
+ const user = notAdmin;
127
+ const {mcpServiceToken, token} = await McpServiceToken.issueFor(user, {name: "Laptop"});
128
+ const app = buildApp({requestLog: true});
129
+
130
+ const res = await callTool(app, "echo_message", {message: "very secret"}, token);
131
+
132
+ expect(res.text).toContain("echo very secret");
133
+ await waitForLogs(1);
134
+ const [row] = await McpRequestLog.find({}).lean();
135
+ expect(row.toolName).toBe("echo_message");
136
+ expect(row.outcome).toBe("ok");
137
+ expect(row.credential).toBe("mcp-service-token");
138
+ expect(String(row.userId)).toBe(String(user._id));
139
+ expect(String(row.serviceTokenId)).toBe(String(mcpServiceToken._id));
140
+ expect(row.durationMs).toBeGreaterThanOrEqual(0);
141
+ expect(row.expiresAt.getTime()).toBeGreaterThan(Date.now() + 6 * 24 * 60 * 60 * 1000);
142
+ const stored = JSON.stringify(row);
143
+ expect(stored).not.toContain("very secret");
144
+ expect(stored).not.toContain(token);
145
+ });
146
+
147
+ it("records an exception by class name without the message", async () => {
148
+ const app = buildApp({requestLog: true});
149
+
150
+ await callTool(app, "always_throws", {});
151
+
152
+ await waitForLogs(1);
153
+ const [row] = await McpRequestLog.find({}).lean();
154
+ expect(row.outcome).toBe("exception");
155
+ expect(row.errorName).toBe("TypeError");
156
+ expect(row.userId).toBeUndefined();
157
+ expect(JSON.stringify(row)).not.toContain("patient 123");
158
+ });
159
+
160
+ it("writes nothing when the log is off", async () => {
161
+ const app = buildApp({});
162
+
163
+ await callTool(app, "echo_message", {message: "hi"});
164
+
165
+ expect(await McpRequestLog.countDocuments({})).toBe(0);
166
+ });
167
+
168
+ it("drops a failed write with a debug log instead of failing the call", async () => {
169
+ const debug = spyOn(logger, "debug");
170
+ try {
171
+ // An outcome outside the schema enum makes the insert fail validation.
172
+ expect(() =>
173
+ recordMcpToolCall(
174
+ {durationMs: 1, outcome: "bogus" as McpRequestLogOutcome, toolName: "echo_message"},
175
+ {retentionDays: 1}
176
+ )
177
+ ).not.toThrow();
178
+ for (let attempt = 0; attempt < 50 && debug.mock.calls.length === 0; attempt++) {
179
+ await new Promise((resolve) => setTimeout(resolve, 10));
180
+ }
181
+ expect(String(debug.mock.calls[0]?.[0])).toContain("Request log write failed");
182
+ expect(await McpRequestLog.countDocuments({})).toBe(0);
183
+ } finally {
184
+ debug.mockRestore();
185
+ }
186
+ });
187
+ });
188
+
189
+ describe("MCP tool settings", () => {
190
+ beforeEach(async () => {
191
+ clearMCPRegistry();
192
+ registerTools();
193
+ await McpToolSetting.deleteMany({});
194
+ });
195
+
196
+ it("registers every tool as enabled on mount", async () => {
197
+ buildApp({toolSettings: true});
198
+
199
+ await waitForSettings(2);
200
+ const rows = await McpToolSetting.find({}).sort({name: 1}).lean();
201
+ expect(rows.map((row) => [row.name, row.enabled, row.source, row.registered])).toEqual([
202
+ ["always_throws", true, "custom", true],
203
+ ["echo_message", true, "custom", true],
204
+ ]);
205
+ });
206
+
207
+ it("keeps an admin's switch across restarts and marks tools that are gone", async () => {
208
+ await McpToolSetting.create({enabled: false, name: "echo_message", source: "custom"});
209
+ await McpToolSetting.create({name: "retired_tool", source: "custom"});
210
+
211
+ await McpToolSetting.syncRegistered([
212
+ {description: "Echo", name: "echo_message", source: "custom"},
213
+ ]);
214
+
215
+ const echo = await McpToolSetting.findExactlyOne({name: "echo_message"});
216
+ expect(echo.enabled).toBe(false);
217
+ expect(echo.registered).toBe(true);
218
+ const retired = await McpToolSetting.findExactlyOne({name: "retired_tool"});
219
+ expect(retired.registered).toBe(false);
220
+ });
221
+
222
+ it("hides a disabled tool from tools/list and rejects tools/call", async () => {
223
+ await McpToolSetting.create({enabled: false, name: "echo_message", source: "custom"});
224
+ const app = buildApp({toolSettings: true});
225
+
226
+ const list = await listTools(app);
227
+ expect(list.text).not.toContain("echo_message");
228
+ expect(list.text).toContain("always_throws");
229
+
230
+ const call = await callTool(app, "echo_message", {message: "hi"});
231
+ expect(call.text).not.toContain("echo hi");
232
+ expect(call.text).toContain("echo_message");
233
+ });
234
+
235
+ it("serves every tool when settings are off, even with a disabled row", async () => {
236
+ await McpToolSetting.create({enabled: false, name: "echo_message", source: "custom"});
237
+ const app = buildApp({});
238
+
239
+ const list = await listTools(app);
240
+
241
+ expect(list.text).toContain("echo_message");
242
+ expect(await McpToolSetting.countDocuments({})).toBe(1);
243
+ expect(mongoose.connection.readyState).toBe(1);
244
+ });
245
+ });
246
+
247
+ describe("TerrenoApp MCP admin options", () => {
248
+ beforeEach(async () => {
249
+ clearMCPRegistry();
250
+ registerTools();
251
+ await McpToolSetting.deleteMany({});
252
+ await McpRequestLog.deleteMany({});
253
+ });
254
+
255
+ it("passes mcpToolSettings and mcpRequestLog through to /mcp", async () => {
256
+ await McpToolSetting.create({enabled: false, name: "always_throws", source: "custom"});
257
+ const app = new TerrenoApp({
258
+ mcpRequestLog: true,
259
+ mcpToolSettings: true,
260
+ skipListen: true,
261
+ userModel: UserModel as unknown as AuthUserModel,
262
+ }).build();
263
+
264
+ const list = await listTools(app);
265
+ expect(list.text).not.toContain("always_throws");
266
+ await callTool(app, "echo_message", {message: "hi"});
267
+
268
+ await waitForLogs(1);
269
+ await waitForSettings(2);
270
+ expect(await McpRequestLog.countDocuments({toolName: "echo_message"})).toBe(1);
271
+ });
272
+ });
@@ -0,0 +1,104 @@
1
+ import {DateTime} from "luxon";
2
+ import mongoose from "mongoose";
3
+
4
+ import {APIError} from "../errors";
5
+ import {logger} from "../logger";
6
+ import {McpRequestLog} from "../models/mcpRequestLog";
7
+ import {McpToolSetting} from "../models/mcpToolSetting";
8
+ import type {McpRequestLogOutcome, McpToolSource} from "../types/mcpAdmin";
9
+ import type {MCPAuthResult} from "./auth";
10
+ import {getMCPCustomTools} from "./registry";
11
+ import type {MCPToolDefinition} from "./toolGenerator";
12
+
13
+ const DEFAULT_REQUEST_LOG_RETENTION_DAYS = 30;
14
+
15
+ /** `true` is `{enabled: true}`. Rows keep metadata only and expire after `retentionDays`. */
16
+ export type McpRequestLogAppOption = boolean | {enabled: boolean; retentionDays?: number};
17
+
18
+ export interface ResolvedMcpRequestLogOptions {
19
+ retentionDays: number;
20
+ }
21
+
22
+ export const resolveMcpRequestLogOption = (
23
+ option: McpRequestLogAppOption | undefined
24
+ ): ResolvedMcpRequestLogOptions | undefined => {
25
+ if (option === true) {
26
+ return {retentionDays: DEFAULT_REQUEST_LOG_RETENTION_DAYS};
27
+ }
28
+ if (!option || typeof option !== "object" || option.enabled !== true) {
29
+ return undefined;
30
+ }
31
+ const retentionDays = option.retentionDays ?? DEFAULT_REQUEST_LOG_RETENTION_DAYS;
32
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
33
+ throw new APIError({
34
+ code: "mcp-request-log-misconfigured",
35
+ detail: `mcpRequestLog.retentionDays must be a positive number, got ${retentionDays}`,
36
+ status: 500,
37
+ title: "MCP request log is misconfigured",
38
+ });
39
+ }
40
+ return {retentionDays};
41
+ };
42
+
43
+ export interface McpToolCallRecord {
44
+ auth?: MCPAuthResult;
45
+ durationMs: number;
46
+ errorName?: string;
47
+ outcome: McpRequestLogOutcome;
48
+ toolName: string;
49
+ }
50
+
51
+ const toObjectId = (value: string | undefined): mongoose.Types.ObjectId | undefined => {
52
+ if (!value || !mongoose.isValidObjectId(value)) {
53
+ return undefined;
54
+ }
55
+ return new mongoose.Types.ObjectId(value);
56
+ };
57
+
58
+ /**
59
+ * Write one request-log row without blocking or failing the tool call. A failed write is
60
+ * logged at debug level and dropped.
61
+ */
62
+ export const recordMcpToolCall = (
63
+ record: McpToolCallRecord,
64
+ options: ResolvedMcpRequestLogOptions
65
+ ): void => {
66
+ const {auth} = record;
67
+ void McpRequestLog.create({
68
+ credential: auth?.credential,
69
+ durationMs: Math.round(record.durationMs),
70
+ errorName: record.errorName,
71
+ expiresAt: DateTime.now().plus({days: options.retentionDays}).toJSDate(),
72
+ oauthClientId: auth?.oauthClientId,
73
+ oauthFamilyId: auth?.oauthFamilyId,
74
+ outcome: record.outcome,
75
+ serviceTokenId: toObjectId(auth?.serviceTokenId),
76
+ toolName: record.toolName,
77
+ userId: toObjectId(auth?.user?.id ? String(auth.user.id) : undefined),
78
+ }).catch((error: unknown) => {
79
+ logger.debug(`[mcp] Request log write failed: ${String(error)}`);
80
+ });
81
+ };
82
+
83
+ /** Register every tool in `McpToolSetting` so admins can see and switch them. */
84
+ export const syncMcpToolSettings = async (tools: MCPToolDefinition[]): Promise<void> => {
85
+ const customNames = new Set(getMCPCustomTools().map((tool) => tool.name));
86
+ await McpToolSetting.syncRegistered(
87
+ tools.map((tool) => ({
88
+ description: tool.description,
89
+ name: tool.name,
90
+ source: (customNames.has(tool.name) ? "custom" : "model") as McpToolSource,
91
+ }))
92
+ );
93
+ };
94
+
95
+ /** Tools an admin left on. A tool without a settings row counts as on. */
96
+ export const filterEnabledMcpTools = async (
97
+ tools: MCPToolDefinition[]
98
+ ): Promise<MCPToolDefinition[]> => {
99
+ const disabled = await McpToolSetting.disabledNames();
100
+ if (disabled.size === 0) {
101
+ return tools;
102
+ }
103
+ return tools.filter((tool) => !disabled.has(tool.name));
104
+ };
package/src/mcp/auth.ts CHANGED
@@ -20,6 +20,12 @@ export interface MCPAuthContext {
20
20
  /** The authenticated user plus the credential type that proved it. */
21
21
  export interface MCPAuthResult {
22
22
  credential: RequestCredential;
23
+ /** OAuth client id for an MCP OAuth access token. Never a secret. */
24
+ oauthClientId?: string;
25
+ /** OAuth rotation-chain id for an MCP OAuth access token. Never a secret. */
26
+ oauthFamilyId?: string;
27
+ /** `McpServiceToken` document id for a service token. Never the token or its hash. */
28
+ serviceTokenId?: string;
23
29
  /** Scopes granted to an MCP OAuth access token; unset for other credentials. */
24
30
  scopes?: string[];
25
31
  user: User;
@@ -97,7 +103,11 @@ const authenticateServiceToken = async (
97
103
  ).catch((error) => {
98
104
  logger.debug(`MCP service token last-used update failed: ${error}`);
99
105
  });
100
- return {credential: "mcp-service-token", user: activeUser};
106
+ return {
107
+ credential: "mcp-service-token",
108
+ serviceTokenId: String(serviceToken._id),
109
+ user: activeUser,
110
+ };
101
111
  };
102
112
 
103
113
  const authenticateOAuthAccessToken = async (
@@ -121,7 +131,13 @@ const authenticateOAuthAccessToken = async (
121
131
  return undefined;
122
132
  }
123
133
  const scopes = (accessToken.scope ?? "").split(" ").filter((scope) => scope.length > 0);
124
- return {credential: "oauth", scopes, user: activeUser};
134
+ return {
135
+ credential: "oauth",
136
+ oauthClientId: accessToken.clientId,
137
+ oauthFamilyId: accessToken.familyId,
138
+ scopes,
139
+ user: activeUser,
140
+ };
125
141
  };
126
142
 
127
143
  /**