@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
@@ -39,8 +39,8 @@ const syncOptions = {
39
39
  read: [Permissions.IsAuthenticated],
40
40
  update: [Permissions.IsAuthenticated],
41
41
  },
42
- sync: {scope: {type: "owner"}},
43
- } as const;
42
+ sync: {scope: {type: "owner" as const}},
43
+ };
44
44
 
45
45
  const baseOptions = {
46
46
  permissions: {
@@ -66,7 +66,7 @@ describe("CollectionRegistry", () => {
66
66
 
67
67
  const record = getCollection("/food");
68
68
  expect(record?.routePath).toBe("/food");
69
- expect(record?.model).toBe(FoodModel);
69
+ expect<unknown>(record?.model).toBe(FoodModel);
70
70
  expect(record?.options).toBe(baseOptions);
71
71
  expect(listCollections()).toHaveLength(1);
72
72
  });
@@ -158,7 +158,7 @@ describe("CollectionRegistry", () => {
158
158
  throw new Error("should not run");
159
159
  });
160
160
  clearCollectionRegistry();
161
- const {ensureSyncIndexes} = await import("./sync/registrationSideEffects");
161
+ const {ensureSyncIndexes} = await import("./sync/registrationSideEffects.js");
162
162
  await expect(ensureSyncIndexes()).resolves.toBeUndefined();
163
163
  });
164
164
  });
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * Process-global catalog of modelRouter collections, keyed by routePath
3
- * (e.g. `/todos`). MCP, realtime, and Sync read this Map instead of each
3
+ * (e.g. `/todos`). MCP and Sync read this Map instead of each
4
4
  * keeping their own list. `modelRouter` is the writer; surface `register*`
5
5
  * / `update*` / `clear*` helpers are wrappers around this module.
6
6
  *
7
7
  * TerrenoApp later injects `accessControl` into options. That patch goes
8
- * through replaceCollectionOptions so all three surfaces see one options
8
+ * through replaceCollectionOptions so every surface sees one options
9
9
  * object. Surface flags stay sticky (OR) so a later replace cannot drop
10
- * mcp/realtime/sync once enabled. First-time sync enable still runs schema
10
+ * mcp/sync once enabled. First-time sync enable still runs schema
11
11
  * and index guards in registrationSideEffects — not here — so catalog
12
12
  * writes stay a Map update.
13
13
  */
@@ -36,7 +36,6 @@ const applyAdminBroadcastDefault = (options: ModelRouterOptions<unknown>): void
36
36
 
37
37
  interface CollectionSurfaces {
38
38
  mcp: boolean;
39
- realtime: boolean;
40
39
  sync: boolean;
41
40
  }
42
41
 
@@ -55,7 +54,6 @@ const deriveSurfaces = (
55
54
  existing?: CollectionSurfaces
56
55
  ): CollectionSurfaces => ({
57
56
  mcp: Boolean(options.mcp) || (existing?.mcp ?? false),
58
- realtime: Boolean(options.realtime) || (existing?.realtime ?? false),
59
57
  sync: Boolean(options.sync) || (existing?.sync ?? false),
60
58
  });
61
59
 
@@ -14,6 +14,7 @@ import {createAccess} from "./rbac/access";
14
14
  import {terrenoStatements} from "./rbac/statements";
15
15
  import {TerrenoApp} from "./terrenoApp";
16
16
  import {authAsUser, setupDb, type User, UserModel} from "./tests";
17
+ import {expectDocumentedResponse} from "./tests/openApiResponseSchema";
17
18
  import type {ConsentFormDocument} from "./types/consentForm";
18
19
 
19
20
  const buildApp = (consentAppOptions: ConsentAppOptions = {}): express.Application =>
@@ -979,6 +980,103 @@ describe("ConsentApp", () => {
979
980
  await noAuditAdmin.get(`/consents/audit/${notAdmin._id}`).expect(404);
980
981
  });
981
982
  });
983
+
984
+ describe("OpenAPI", () => {
985
+ interface SchemaNode {
986
+ items?: SchemaNode;
987
+ properties?: Record<string, SchemaNode>;
988
+ required?: string[];
989
+ type?: string;
990
+ }
991
+
992
+ const responseSchema = (
993
+ paths: Record<string, Record<string, {responses: Record<string, unknown>}>>,
994
+ path: string,
995
+ method: string
996
+ ): SchemaNode | undefined => {
997
+ const response = paths[path]?.[method]?.responses["200"] as
998
+ | {content?: Record<string, {schema: SchemaNode}>}
999
+ | undefined;
1000
+ return response?.content?.["application/json"]?.schema;
1001
+ };
1002
+
1003
+ it("documents GET /consents/pending and POST /consents/respond", async () => {
1004
+ const res = await supertest(buildApp()).get("/openapi.json").expect(200);
1005
+ const paths = res.body.paths;
1006
+
1007
+ const pending = responseSchema(paths, "/consents/pending", "get");
1008
+ expect(pending?.required).toEqual(["data"]);
1009
+ expect(pending?.properties?.data?.type).toBe("array");
1010
+ const formItem = pending?.properties?.data?.items;
1011
+ expect(formItem?.properties?.slug?.type).toBe("string");
1012
+ expect(formItem?.properties?.version?.type).toBe("number");
1013
+ expect(formItem?.properties?.id?.type).toBe("string");
1014
+
1015
+ const respond = paths["/consents/respond"]?.post;
1016
+ const body = respond?.requestBody?.content?.["application/json"]?.schema;
1017
+ expect(body?.required).toEqual(["agreed", "consentFormId", "locale"]);
1018
+ expect(body?.properties?.agreed?.type).toBe("boolean");
1019
+ expect(body?.properties?.checkboxValues?.additionalProperties).toEqual({type: "boolean"});
1020
+ expect(body?.properties?.signature?.type).toBe("string");
1021
+ const respondData = responseSchema(paths, "/consents/respond", "post")?.properties?.data;
1022
+ expect(respondData?.properties?.agreed?.type).toBe("boolean");
1023
+ expect(respondData?.properties?.consentFormId).toBeDefined();
1024
+ });
1025
+
1026
+ it("documents every field the consent routes return", async () => {
1027
+ const app = buildApp({auditTrail: true});
1028
+ const docRes = await supertest(app).get("/openapi.json").expect(200);
1029
+ const paths = docRes.body.paths;
1030
+ const form = await ConsentForm.create({
1031
+ active: true,
1032
+ captureSignature: true,
1033
+ content: new Map([["en", "# Terms"]]),
1034
+ order: 1,
1035
+ slug: "openapi-terms",
1036
+ title: "Terms",
1037
+ type: "terms",
1038
+ version: 1,
1039
+ });
1040
+ const agent = await authAsUser(app, "notAdmin");
1041
+
1042
+ const pendingRes = await agent.get("/consents/pending").expect(200);
1043
+ expectDocumentedResponse({
1044
+ method: "get",
1045
+ path: "/consents/pending",
1046
+ response: pendingRes,
1047
+ spec: docRes.body,
1048
+ });
1049
+ const pendingDocumented = Object.keys(
1050
+ responseSchema(paths, "/consents/pending", "get")?.properties?.data?.items?.properties ?? {}
1051
+ );
1052
+ expect(pendingDocumented).toEqual(
1053
+ expect.arrayContaining(Object.keys(pendingRes.body.data[0]).filter((key) => key !== "__v"))
1054
+ );
1055
+
1056
+ const respondRes = await agent
1057
+ .post("/consents/respond")
1058
+ .send({
1059
+ agreed: true,
1060
+ consentFormId: form._id,
1061
+ locale: "en",
1062
+ signature: "data:image/png;base64,AA",
1063
+ })
1064
+ .expect(200);
1065
+ expectDocumentedResponse({
1066
+ method: "post",
1067
+ path: "/consents/respond",
1068
+ response: respondRes,
1069
+ spec: docRes.body,
1070
+ });
1071
+ const respondDocumented = Object.keys(
1072
+ responseSchema(paths, "/consents/respond", "post")?.properties?.data?.properties ?? {}
1073
+ );
1074
+ expect(respondDocumented).toEqual(
1075
+ expect.arrayContaining(Object.keys(respondRes.body.data).filter((key) => key !== "__v"))
1076
+ );
1077
+ });
1078
+ });
1079
+
982
1080
  describe("POST /consent-responses/provisional", () => {
983
1081
  const createActiveForm = async (
984
1082
  overrides: Partial<Record<string, unknown>> = {}
package/src/consentApp.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * endpoints for fetching pending consents and submitting responses.
7
7
  */
8
8
 
9
- import {type Application, Router} from "express";
9
+ import {type Application, type RequestHandler, Router} from "express";
10
10
  import {DateTime} from "luxon";
11
11
  import type mongoose from "mongoose";
12
12
  import type {CollectionActionConfig} from "./actions";
@@ -27,8 +27,9 @@ import {APIError} from "./errors";
27
27
  import {logger} from "./logger";
28
28
  import {ConsentForm} from "./models/consentForm";
29
29
  import {ConsentResponse} from "./models/consentResponse";
30
+ import {createOpenApiBuilder, type OpenApiSchemaProperty} from "./openApiBuilder";
30
31
  import {type PermissionMethod, Permissions} from "./permissions";
31
- import type {PopulatePath} from "./populate";
32
+ import {getOpenApiSpecForModel, type PopulatePath} from "./populate";
32
33
  import type {AnyTerrenoAccess} from "./rbac/types";
33
34
  import type {TerrenoPlugin} from "./terrenoPlugin";
34
35
  import type {ConsentFormDocument} from "./types/consentForm";
@@ -52,6 +53,67 @@ export const consentResponsePopulatePaths: PopulatePath[] = [
52
53
  },
53
54
  ];
54
55
 
56
+ /** A consent document as `toJSON` serializes it: model fields plus the `id` virtual. */
57
+ const consentDocumentOpenApiSchema = (model: mongoose.Model<unknown>): OpenApiSchemaProperty => {
58
+ const {properties, required} = getOpenApiSpecForModel(model);
59
+ return {
60
+ properties: {
61
+ ...(properties as Record<string, OpenApiSchemaProperty>),
62
+ id: {description: "The document id, the same value as _id", type: "string"},
63
+ },
64
+ required: Array.from(new Set([...required, "_id", "id"])),
65
+ type: "object",
66
+ };
67
+ };
68
+
69
+ /** Documentation only: request validation stays off so the handlers behave as before. */
70
+ const buildConsentOpenApi = (
71
+ openApi: OpenApiMiddleware | undefined
72
+ ): {pending: RequestHandler; respond: RequestHandler} => {
73
+ const noop: RequestHandler = (_req, _res, next) => next();
74
+ if (!openApi?.path) {
75
+ return {pending: noop, respond: noop};
76
+ }
77
+ const consentForm = consentDocumentOpenApiSchema(
78
+ ConsentForm as unknown as mongoose.Model<unknown>
79
+ );
80
+ const consentResponse = consentDocumentOpenApiSchema(
81
+ ConsentResponse as unknown as mongoose.Model<unknown>
82
+ );
83
+ return {
84
+ pending: createOpenApiBuilder({openApi})
85
+ .withTags(["consents"])
86
+ .withSummary("List active consent forms the current user still has to answer")
87
+ .withResponse(200, {data: {items: consentForm, type: "array"}}, {required: ["data"]})
88
+ .withValidation({enabled: false})
89
+ .build(),
90
+ respond: createOpenApiBuilder({openApi})
91
+ .withTags(["consents"])
92
+ .withSummary("Submit the current user's response to a consent form")
93
+ .withRequestBody({
94
+ agreed: {description: "Whether the user agreed", required: true, type: "boolean"},
95
+ checkboxValues: {
96
+ additionalProperties: {type: "boolean"},
97
+ description: "Checkbox index (as a string) to whether it was checked",
98
+ type: "object",
99
+ },
100
+ consentFormId: {
101
+ description: "The consent form being answered",
102
+ required: true,
103
+ type: "string",
104
+ },
105
+ locale: {description: "Locale the form was shown in", required: true, type: "string"},
106
+ signature: {
107
+ description: "Signature image data, required when the form captures a signature",
108
+ type: "string",
109
+ },
110
+ })
111
+ .withResponse(200, {data: consentResponse}, {required: ["data"]})
112
+ .withValidation({enabled: false})
113
+ .build(),
114
+ };
115
+ };
116
+
55
117
  const PROVISIONAL_NOTE_MAX_LENGTH = 2000;
56
118
 
57
119
  const provisionalSignBody = z
@@ -356,6 +418,7 @@ export class ConsentApp implements TerrenoPlugin {
356
418
 
357
419
  register(app: Application, openApi?: unknown): void {
358
420
  const {accessControl, auditTrail, resolveConsentForms, aiConfig} = this.options;
421
+ const consentOpenApi = buildConsentOpenApi(openApi as OpenApiMiddleware | undefined);
359
422
 
360
423
  if (!accessControl) {
361
424
  logger.warn(
@@ -682,6 +745,7 @@ export class ConsentApp implements TerrenoPlugin {
682
745
  router.get(
683
746
  "/pending",
684
747
  authenticateMiddleware(),
748
+ consentOpenApi.pending,
685
749
  asyncHandler(async (req, res) => {
686
750
  const user = req.user as User | undefined;
687
751
  if (!user) {
@@ -768,6 +832,7 @@ export class ConsentApp implements TerrenoPlugin {
768
832
  router.post(
769
833
  "/respond",
770
834
  authenticateMiddleware(),
835
+ consentOpenApi.respond,
771
836
  asyncHandler(async (req, res) => {
772
837
  const user = req.user as User | undefined;
773
838
  if (!user) {
@@ -5,7 +5,11 @@ import mongoose from "mongoose";
5
5
  import {createAuditEventModel} from "./audit/auditEventModel";
6
6
  import {AuthToken} from "./authTokens";
7
7
  import {FRAMEWORK_MODEL_PUBLIC_NAMES, publicFrameworkModelName} from "./frameworkModelNames";
8
+ import {McpOAuthClient} from "./models/mcpOAuthClient";
9
+ import {McpOAuthToken} from "./models/mcpOAuthToken";
10
+ import {McpRequestLog} from "./models/mcpRequestLog";
8
11
  import {McpServiceToken} from "./models/mcpServiceToken";
12
+ import {McpToolSetting} from "./models/mcpToolSetting";
9
13
  import {Notification} from "./models/notification";
10
14
  import {NotificationPreference} from "./models/notificationPreference";
11
15
  import {getMembershipModel, getOrganizationModel} from "./orgs/organizationModel";
@@ -35,7 +39,11 @@ describe("framework model names", () => {
35
39
  const models = [
36
40
  [createAuditEventModel(mongoose.connection), "TerrenoAuditEvent", "auditevents"],
37
41
  [AuthToken, "TerrenoAuthToken", "authtokens"],
42
+ [McpOAuthClient, "TerrenoMcpOAuthClient", "mcpoauthclients"],
43
+ [McpOAuthToken, "TerrenoMcpOAuthToken", "mcpoauthtokens"],
44
+ [McpRequestLog, "TerrenoMcpRequestLog", "mcprequestlogs"],
38
45
  [McpServiceToken, "TerrenoMcpServiceToken", "mcpservicetokens"],
46
+ [McpToolSetting, "TerrenoMcpToolSetting", "mcptoolsettings"],
39
47
  [getMembershipModel(), "TerrenoMembership", "memberships"],
40
48
  [Notification, "TerrenoInboxNotification", "notifications"],
41
49
  [NotificationPreference, "TerrenoNotificationPreference", "notificationpreferences"],
@@ -9,7 +9,11 @@ export const FRAMEWORK_MODEL_PUBLIC_NAMES = {
9
9
  TerrenoInboxNotification: "Notification",
10
10
  TerrenoJob: "Job",
11
11
  TerrenoJobSchedule: "JobSchedule",
12
+ TerrenoMcpOAuthClient: "McpOAuthClient",
13
+ TerrenoMcpOAuthToken: "McpOAuthToken",
14
+ TerrenoMcpRequestLog: "McpRequestLog",
12
15
  TerrenoMcpServiceToken: "McpServiceToken",
16
+ TerrenoMcpToolSetting: "McpToolSetting",
13
17
  TerrenoMembership: "Membership",
14
18
  TerrenoNotificationPreference: "NotificationPreference",
15
19
  TerrenoOrganization: "Organization",
@@ -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
@@ -81,6 +81,11 @@ export {
81
81
  export * from "./githubAuth";
82
82
  export * from "./httpClient";
83
83
  export * from "./logger";
84
+ export {
85
+ type McpRequestLogAppOption,
86
+ type ResolvedMcpRequestLogOptions,
87
+ resolveMcpRequestLogOption,
88
+ } from "./mcp/adminTracking";
84
89
  export {
85
90
  extractAuthFromHeaders,
86
91
  extractUserFromHeaders,
@@ -109,10 +114,14 @@ export {generateInputSchema, generateToolDescription} from "./mcp/schemaGenerato
109
114
  export {type MCPServerOptions, mountMCPServer} from "./mcp/server";
110
115
  export {
111
116
  addMcpServiceTokenRoutes,
117
+ createMcpServiceTokenRouter,
112
118
  MAX_ACTIVE_MCP_SERVICE_TOKENS,
119
+ MCP_SERVICE_TOKENS_ROUTE_PATH,
120
+ MCP_SERVICE_TOKENS_SYNC_COLLECTION,
113
121
  type McpServiceTokenRoutesOptions,
114
122
  type McpServiceTokensAppOption,
115
123
  resolveMcpServiceTokensOption,
124
+ toPublicMcpServiceToken,
116
125
  } from "./mcp/serviceTokens";
117
126
  export {
118
127
  generateAllTools,
@@ -129,6 +138,7 @@ export type {
129
138
  MCPToolResult,
130
139
  } from "./mcp/types";
131
140
  export * from "./middleware";
141
+ export * from "./migrations/builtin/mcpServiceTokenStringIds";
132
142
  export * from "./migrations/generate";
133
143
  export * from "./migrations/load";
134
144
  export * from "./migrations/lock";
@@ -141,7 +151,9 @@ export {McpOAuthAuthorization} from "./models/mcpOAuthAuthorization";
141
151
  export {McpOAuthClient} from "./models/mcpOAuthClient";
142
152
  export {McpOAuthRevokedFamily} from "./models/mcpOAuthRevokedFamily";
143
153
  export {McpOAuthFamilyRevokedError, McpOAuthToken} from "./models/mcpOAuthToken";
154
+ export {McpRequestLog} from "./models/mcpRequestLog";
144
155
  export * from "./models/mcpServiceToken";
156
+ export {McpToolSetting} from "./models/mcpToolSetting";
145
157
  export * from "./models/notification";
146
158
  export * from "./models/notificationPreference";
147
159
  export * from "./models/versionConfig";
@@ -246,31 +258,11 @@ export {
246
258
  stopChangeStreamWatcher,
247
259
  } from "./realtime/changeStreamWatcher";
248
260
  export {matchesQuery} from "./realtime/queryMatcher";
249
- export {
250
- addQuerySubscription,
251
- clearQueryStore,
252
- computeQueryId,
253
- getQuerySubscriptionsForCollection,
254
- removeAllSocketQueries,
255
- removeQuerySubscription,
256
- } from "./realtime/queryStore";
257
261
  export {
258
262
  installRealtimeSocketHandlers,
259
- MAX_DOCUMENT_SUBSCRIPTIONS,
260
- MAX_MODEL_SUBSCRIPTIONS,
261
- MAX_QUERY_SUBSCRIPTIONS,
262
263
  RealtimeApp,
263
264
  type RealtimeSocketLike,
264
265
  } from "./realtime/realtimeApp";
265
- export {
266
- clearRealtimeRegistry,
267
- findRegistryEntryByCollection,
268
- findRegistryEntryByRoutePath,
269
- getRealtimeRegistry,
270
- type RealtimeRegistryEntry,
271
- registerRealtime,
272
- updateRealtimeRegistryOptions,
273
- } from "./realtime/registry";
274
266
  export {
275
267
  DEFAULT_SESSION_REVALIDATION_INTERVAL_MS,
276
268
  loadFullUserForSocket,
@@ -297,14 +289,7 @@ export {
297
289
  type SocketDataBag,
298
290
  type SocketWithDecodedToken,
299
291
  } from "./realtime/socketUser";
300
- export type {
301
- ChangeStreamConfig,
302
- DocumentSubscription,
303
- QuerySubscription,
304
- RealtimeAppOptions,
305
- RealtimeConfig,
306
- RealtimeEvent,
307
- } from "./realtime/types";
292
+ export type {ChangeStreamConfig, RealtimeAppOptions} from "./realtime/types";
308
293
  export * from "./requestContext";
309
294
  export {
310
295
  type DescribeModelForRouterOptions,
@@ -347,6 +332,7 @@ export * from "./terrenoPlugin";
347
332
  export * from "./transformers";
348
333
  export * from "./types/consentForm";
349
334
  export * from "./types/consentResponse";
335
+ export type * from "./types/mcpAdmin";
350
336
  export type {
351
337
  McpOAuthAuthorizationDocument,
352
338
  McpOAuthAuthorizationStatus,
@@ -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"},
@@ -161,7 +167,7 @@ describe("modelRouter actions as MCP tools", () => {
161
167
  const [, notAdmin] = await setupDb();
162
168
  ownerId = notAdmin._id as mongoose.Types.ObjectId;
163
169
  await WidgetModel.deleteMany({});
164
- await McpServiceToken.deleteMany({});
170
+ await McpServiceToken.collection.deleteMany({});
165
171
  clearMCPRegistry();
166
172
  app = new TerrenoApp({mcpServiceTokens: true, skipListen: true, userModel: typedUserModel})
167
173
  .register(widgetRouter())
@@ -314,7 +320,7 @@ describe("modelRouter actions as MCP tools", () => {
314
320
  });
315
321
 
316
322
  it("records the credential type inside the tool handler", async () => {
317
- const created = await ownerAgent.post("/mcp/service-tokens").send({name: "Agent"});
323
+ const created = await ownerAgent.post("/mcp/service-tokens/create").send({name: "Agent"});
318
324
  const serviceToken = created.body.data.token as string;
319
325
 
320
326
  const jwtResult = await callTool(ownerAgent, "widgets_count_mine", {});