@terreno/api 57.2.0 → 57.3.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 (277) hide show
  1. package/README.md +17 -7
  2. package/dist/actions.js +19 -7
  3. package/dist/api.d.ts +4 -0
  4. package/dist/api.js +12 -24
  5. package/dist/auth.d.ts +23 -10
  6. package/dist/auth.js +97 -32
  7. package/dist/authRecovery.d.ts +5 -0
  8. package/dist/authRecovery.js +350 -0
  9. package/dist/authTokens.d.ts +8 -0
  10. package/dist/authTokens.js +162 -0
  11. package/dist/betterAuth.d.ts +33 -0
  12. package/dist/betterAuthApp.d.ts +4 -0
  13. package/dist/betterAuthApp.js +26 -8
  14. package/dist/betterAuthSetup.d.ts +44 -2
  15. package/dist/betterAuthSetup.js +288 -18
  16. package/dist/collectionRegistry.d.ts +38 -0
  17. package/dist/collectionRegistry.js +72 -0
  18. package/dist/configurationApp.d.ts +11 -2
  19. package/dist/configurationApp.js +2 -4
  20. package/dist/docLoader.js +35 -6
  21. package/dist/expressServer.d.ts +26 -3
  22. package/dist/expressServer.js +79 -11
  23. package/dist/index.d.ts +16 -0
  24. package/dist/index.js +38 -2
  25. package/dist/mcp/auth.d.ts +1 -0
  26. package/dist/mcp/auth.js +47 -25
  27. package/dist/mcp/handlers.d.ts +1 -1
  28. package/dist/mcp/handlers.js +67 -233
  29. package/dist/mcp/query.d.ts +2 -2
  30. package/dist/mcp/registry.d.ts +1 -5
  31. package/dist/mcp/registry.js +31 -20
  32. package/dist/mcp/schemaGenerator.d.ts +2 -7
  33. package/dist/mcp/schemaGenerator.js +41 -116
  34. package/dist/mcp/server.d.ts +1 -0
  35. package/dist/mcp/server.js +1 -0
  36. package/dist/mcp/serviceTokens.d.ts +16 -0
  37. package/dist/mcp/serviceTokens.js +345 -0
  38. package/dist/mcp/types.d.ts +2 -2
  39. package/dist/models/mcpServiceToken.d.ts +3 -0
  40. package/dist/models/mcpServiceToken.js +208 -0
  41. package/dist/openApiBuilder.d.ts +5 -4
  42. package/dist/openApiBuilder.js +61 -8
  43. package/dist/openApiCompat.js +1 -1
  44. package/dist/openApiValidator.js +0 -2
  45. package/dist/plugins.d.ts +14 -1
  46. package/dist/plugins.js +17 -6
  47. package/dist/populate.d.ts +2 -2
  48. package/dist/populate.js +47 -42
  49. package/dist/rateLimit/applyTrustProxy.d.ts +3 -0
  50. package/dist/rateLimit/applyTrustProxy.js +17 -0
  51. package/dist/rateLimit/createStore.d.ts +2 -0
  52. package/dist/rateLimit/createStore.js +28 -0
  53. package/dist/rateLimit/memoryStore.d.ts +2 -0
  54. package/dist/rateLimit/memoryStore.js +108 -0
  55. package/dist/rateLimit/middleware.d.ts +11 -0
  56. package/dist/rateLimit/middleware.js +110 -0
  57. package/dist/rateLimit/mongoStore.d.ts +3 -0
  58. package/dist/rateLimit/mongoStore.js +122 -0
  59. package/dist/rateLimit/policies.d.ts +14 -0
  60. package/dist/rateLimit/policies.js +151 -0
  61. package/dist/rateLimit/redisStore.d.ts +3 -0
  62. package/dist/rateLimit/redisStore.js +155 -0
  63. package/dist/rateLimit/types.d.ts +54 -0
  64. package/dist/rateLimit/types.js +9 -0
  65. package/dist/rbac/access.js +5 -1
  66. package/dist/rbac/assertAllowed.d.ts +9 -0
  67. package/dist/rbac/assertAllowed.js +182 -0
  68. package/dist/rbac/modelRouterAccess.d.ts +1 -0
  69. package/dist/rbac/modelRouterAccess.js +8 -4
  70. package/dist/rbac/permissionUtils.js +3 -2
  71. package/dist/rbac/resolve.js +5 -4
  72. package/dist/rbac/routes.js +15 -6
  73. package/dist/realtime/deprecation.d.ts +12 -0
  74. package/dist/realtime/deprecation.js +32 -0
  75. package/dist/realtime/realtimeApp.d.ts +1 -1
  76. package/dist/realtime/realtimeApp.js +10 -11
  77. package/dist/realtime/registry.d.ts +0 -31
  78. package/dist/realtime/registry.js +44 -31
  79. package/dist/realtime/socketAuth.d.ts +5 -5
  80. package/dist/realtime/socketAuth.js +11 -1
  81. package/dist/realtime/socketUser.d.ts +5 -1
  82. package/dist/realtime/types.d.ts +14 -4
  83. package/dist/schemaMetadata.d.ts +56 -0
  84. package/dist/schemaMetadata.js +513 -0
  85. package/dist/seedRunner.d.ts +88 -0
  86. package/dist/seedRunner.js +627 -0
  87. package/dist/sync/executors.d.ts +12 -2
  88. package/dist/sync/executors.js +8 -10
  89. package/dist/sync/loadHarness.js +28 -19
  90. package/dist/sync/models.js +26 -24
  91. package/dist/sync/mutationHandler.d.ts +9 -0
  92. package/dist/sync/mutationHandler.js +11 -6
  93. package/dist/sync/registrationSideEffects.d.ts +35 -0
  94. package/dist/sync/registrationSideEffects.js +151 -0
  95. package/dist/sync/registry.d.ts +2 -52
  96. package/dist/sync/registry.js +38 -187
  97. package/dist/sync/routes.js +3 -2
  98. package/dist/sync/scripts/compactTombstones.js +0 -2
  99. package/dist/sync/syncApp.d.ts +3 -3
  100. package/dist/sync/syncApp.js +4 -4
  101. package/dist/sync/syncBatch.js +3 -2
  102. package/dist/sync/syncSeqPlugin.d.ts +1 -1
  103. package/dist/sync/syncSeqPlugin.js +20 -16
  104. package/dist/terrenoApp.d.ts +19 -5
  105. package/dist/terrenoApp.js +66 -18
  106. package/dist/tests/models.d.ts +2 -0
  107. package/dist/tests/models.js +6 -0
  108. package/dist/types/authToken.d.ts +33 -0
  109. package/dist/types/authToken.js +2 -0
  110. package/dist/types/mcpServiceToken.d.ts +41 -0
  111. package/dist/types/mcpServiceToken.js +2 -0
  112. package/dist/webhooks/headerValue.d.ts +2 -0
  113. package/dist/webhooks/headerValue.js +14 -0
  114. package/dist/webhooks/idempotency/memoryStore.d.ts +10 -0
  115. package/dist/webhooks/idempotency/memoryStore.js +65 -0
  116. package/dist/webhooks/idempotency/mongoStore.d.ts +4 -0
  117. package/dist/webhooks/idempotency/mongoStore.js +150 -0
  118. package/dist/webhooks/idempotency/webhookReceipt.d.ts +62 -0
  119. package/dist/webhooks/idempotency/webhookReceipt.js +39 -0
  120. package/dist/webhooks/rawBody.d.ts +14 -0
  121. package/dist/webhooks/rawBody.js +22 -0
  122. package/dist/webhooks/timingSafeEqual.d.ts +4 -0
  123. package/dist/webhooks/timingSafeEqual.js +17 -0
  124. package/dist/webhooks/verifiers/hmac.d.ts +15 -0
  125. package/dist/webhooks/verifiers/hmac.js +49 -0
  126. package/dist/webhooks/verifiers/sendgrid.d.ts +10 -0
  127. package/dist/webhooks/verifiers/sendgrid.js +56 -0
  128. package/dist/webhooks/verifiers/stripe.d.ts +9 -0
  129. package/dist/webhooks/verifiers/stripe.js +99 -0
  130. package/dist/webhooks/verifiers/twilio.d.ts +9 -0
  131. package/dist/webhooks/verifiers/twilio.js +112 -0
  132. package/dist/webhooks/webhooksApp.d.ts +33 -0
  133. package/dist/webhooks/webhooksApp.js +195 -0
  134. package/package.json +4 -5
  135. package/src/__snapshots__/openApi.test.ts.snap +270 -0
  136. package/src/__snapshots__/openApiBuilder.test.ts.snap +30 -12
  137. package/src/__snapshots__/schemaMetadata.test.ts.snap +197 -0
  138. package/src/actions.ts +20 -13
  139. package/src/adminModelRouter.test.ts +133 -0
  140. package/src/api.arrayOperations.test.ts +43 -31
  141. package/src/api.hooks.test.ts +38 -29
  142. package/src/api.query.test.ts +31 -31
  143. package/src/api.test.ts +95 -96
  144. package/src/api.ts +16 -27
  145. package/src/auth.test.ts +107 -51
  146. package/src/auth.ts +98 -29
  147. package/src/authRecovery.test.ts +281 -0
  148. package/src/authRecovery.ts +279 -0
  149. package/src/authTokens.test.ts +94 -0
  150. package/src/authTokens.ts +118 -0
  151. package/src/authVerification.test.ts +293 -0
  152. package/src/betterAuth.ts +24 -0
  153. package/src/betterAuthApp.test.ts +1 -0
  154. package/src/betterAuthApp.ts +27 -9
  155. package/src/betterAuthSetup.test.ts +568 -38
  156. package/src/betterAuthSetup.ts +260 -5
  157. package/src/collectionRegistry.test.ts +165 -0
  158. package/src/collectionRegistry.ts +115 -0
  159. package/src/configurationApp.ts +13 -7
  160. package/src/docLoader.test.ts +45 -1
  161. package/src/docLoader.ts +37 -6
  162. package/src/express.d.ts +1 -0
  163. package/src/expressServer.test.ts +130 -66
  164. package/src/expressServer.ts +75 -19
  165. package/src/githubAuth.test.ts +60 -55
  166. package/src/index.ts +58 -0
  167. package/src/mcp/auth.test.ts +47 -0
  168. package/src/mcp/auth.ts +32 -11
  169. package/src/mcp/handlers.ts +45 -172
  170. package/src/mcp/integration.test.ts +59 -9
  171. package/src/mcp/query.ts +2 -4
  172. package/src/mcp/registry.ts +29 -20
  173. package/src/mcp/schemaGenerator.test.ts +8 -0
  174. package/src/mcp/schemaGenerator.ts +49 -131
  175. package/src/mcp/server.ts +2 -0
  176. package/src/mcp/serviceTokens.test.ts +330 -0
  177. package/src/mcp/serviceTokens.ts +307 -0
  178. package/src/mcp/toolGenerator.test.ts +1 -1
  179. package/src/mcp/types.ts +2 -6
  180. package/src/models/mcpServiceToken.test.ts +129 -0
  181. package/src/models/mcpServiceToken.ts +158 -0
  182. package/src/openApi.test.ts +80 -64
  183. package/src/openApiBuilder.test.ts +95 -7
  184. package/src/openApiBuilder.ts +46 -9
  185. package/src/openApiCompat.ts +1 -1
  186. package/src/openApiValidator.test.ts +49 -54
  187. package/src/openApiValidator.ts +1 -3
  188. package/src/plugins.test.ts +14 -0
  189. package/src/plugins.ts +34 -9
  190. package/src/populate.test.ts +34 -0
  191. package/src/populate.ts +40 -29
  192. package/src/rateLimit/applyTrustProxy.ts +17 -0
  193. package/src/rateLimit/createStore.ts +25 -0
  194. package/src/rateLimit/memoryStore.ts +40 -0
  195. package/src/rateLimit/middleware.ts +79 -0
  196. package/src/rateLimit/mongoStore.test.ts +80 -0
  197. package/src/rateLimit/mongoStore.ts +76 -0
  198. package/src/rateLimit/policies.ts +130 -0
  199. package/src/rateLimit/rateLimit.test.ts +328 -0
  200. package/src/rateLimit/redisStore.ioredis.test.ts +29 -0
  201. package/src/rateLimit/redisStore.test.ts +114 -0
  202. package/src/rateLimit/redisStore.ts +85 -0
  203. package/src/rateLimit/types.ts +64 -0
  204. package/src/rbac/access.ts +5 -1
  205. package/src/rbac/assertAllowed.test.ts +325 -0
  206. package/src/rbac/assertAllowed.ts +157 -0
  207. package/src/rbac/backfillAdmins.test.ts +124 -0
  208. package/src/rbac/fieldViews.test.ts +89 -0
  209. package/src/rbac/modelRouterAccess.test.ts +126 -0
  210. package/src/rbac/modelRouterAccess.ts +5 -2
  211. package/src/rbac/permissionUtils.ts +3 -2
  212. package/src/rbac/realtimeAccess.test.ts +109 -1
  213. package/src/rbac/resolve.ts +5 -4
  214. package/src/rbac/roleManager.test.ts +169 -0
  215. package/src/rbac/routes.test.ts +233 -0
  216. package/src/rbac/routes.ts +16 -6
  217. package/src/realtime/deprecation.test.ts +60 -0
  218. package/src/realtime/deprecation.ts +32 -0
  219. package/src/realtime/realtime.test.ts +8 -4
  220. package/src/realtime/realtimeApp.ts +10 -11
  221. package/src/realtime/realtimeAppSetup.test.ts +32 -5
  222. package/src/realtime/registry.ts +48 -42
  223. package/src/realtime/sessionRevalidation.test.ts +57 -44
  224. package/src/realtime/socketAuth.test.ts +75 -23
  225. package/src/realtime/socketAuth.ts +17 -6
  226. package/src/realtime/socketUser.ts +5 -3
  227. package/src/realtime/types.ts +14 -4
  228. package/src/schemaMetadata.test.ts +405 -0
  229. package/src/schemaMetadata.ts +593 -0
  230. package/src/scrubAdminFields.test.ts +105 -0
  231. package/src/seedRunner.test.ts +591 -0
  232. package/src/seedRunner.ts +464 -0
  233. package/src/sync/docMatchesMutationData.test.ts +16 -0
  234. package/src/sync/ensureSyncIndexes.test.ts +54 -15
  235. package/src/sync/executors.test.ts +40 -0
  236. package/src/sync/executors.ts +24 -12
  237. package/src/sync/integration.test.ts +15 -7
  238. package/src/sync/loadHarness.ts +28 -19
  239. package/src/sync/models.ts +32 -18
  240. package/src/sync/mutationHandler.test.ts +16 -16
  241. package/src/sync/mutationHandler.ts +9 -7
  242. package/src/sync/registrationSideEffects.test.ts +126 -0
  243. package/src/sync/registrationSideEffects.ts +131 -0
  244. package/src/sync/registry.ts +45 -171
  245. package/src/sync/routes.ts +3 -2
  246. package/src/sync/scripts/compactTombstones.ts +0 -2
  247. package/src/sync/sessionRevalidationIntegration.test.ts +12 -11
  248. package/src/sync/sync.test.ts +25 -23
  249. package/src/sync/syncApp.ts +4 -4
  250. package/src/sync/syncBatch.ts +3 -2
  251. package/src/sync/syncFrontier.test.ts +17 -15
  252. package/src/sync/syncPhaseC.test.ts +54 -43
  253. package/src/sync/syncRoutes.test.ts +51 -36
  254. package/src/sync/syncSeqPlugin.ts +66 -44
  255. package/src/sync/syncSocket.test.ts +112 -81
  256. package/src/terrenoApp.mcpServiceTokens.test.ts +173 -0
  257. package/src/terrenoApp.ts +87 -15
  258. package/src/tests/models.ts +14 -1
  259. package/src/types/authToken.ts +43 -0
  260. package/src/types/mcpServiceToken.ts +54 -0
  261. package/src/webhooks/headerValue.test.ts +22 -0
  262. package/src/webhooks/headerValue.ts +12 -0
  263. package/src/webhooks/idempotency/memoryStore.ts +34 -0
  264. package/src/webhooks/idempotency/mongoStore.test.ts +274 -0
  265. package/src/webhooks/idempotency/mongoStore.ts +83 -0
  266. package/src/webhooks/idempotency/webhookReceipt.ts +70 -0
  267. package/src/webhooks/rawBody.test.ts +74 -0
  268. package/src/webhooks/rawBody.ts +23 -0
  269. package/src/webhooks/timingSafeEqual.ts +16 -0
  270. package/src/webhooks/verifiers/hmac.test.ts +110 -0
  271. package/src/webhooks/verifiers/hmac.ts +54 -0
  272. package/src/webhooks/verifiers/providerVerifiers.test.ts +388 -0
  273. package/src/webhooks/verifiers/sendgrid.ts +59 -0
  274. package/src/webhooks/verifiers/stripe.ts +67 -0
  275. package/src/webhooks/verifiers/twilio.ts +69 -0
  276. package/src/webhooks/webhooksApp.test.ts +221 -0
  277. package/src/webhooks/webhooksApp.ts +144 -0
@@ -2,88 +2,29 @@ import type {Model} from "mongoose";
2
2
  import {type ZodType, z} from "zod";
3
3
 
4
4
  import type {PopulatePath} from "../populate";
5
+ import {
6
+ describeModel,
7
+ type FieldDescription,
8
+ fieldDescriptionToZodType,
9
+ SYSTEM_FIELD_PATHS,
10
+ } from "../schemaMetadata";
5
11
  import type {MCPConfig, MCPMethod} from "./types";
6
12
 
7
- const SYSTEM_FIELDS = new Set(["_id", "id", "__v", "created", "updated", "deleted"]);
8
-
9
- /** Shown to the calling LLM so it knows filters accept Mongo comparison operators. */
10
13
  const OPERATOR_HINT = `{"$in": [...]} or {"$gte": ...}`;
11
-
12
- /** Operators an LLM may use in a list filter, kept in sync with ALLOWED_FIELD_OPERATORS. */
13
14
  const DOCUMENTED_FIELD_OPERATORS = "$eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $exists, $regex";
14
15
 
15
- /** The subset of Mongoose SchemaType internals used to derive MCP tool schemas. */
16
- interface MongooseSchemaPath {
17
- caster?: {instance?: string; options?: {description?: string; ref?: string}};
18
- enumValues?: string[];
19
- instance?: string;
20
- isRequired?: boolean;
21
- options?: {description?: string; ref?: string};
22
- schema?: unknown;
23
- }
24
-
25
16
  interface ModelField {
17
+ description?: string;
18
+ field: FieldDescription;
26
19
  path: string;
27
- schemaPath: MongooseSchemaPath;
28
20
  required: boolean;
29
- description?: string;
30
21
  }
31
22
 
32
- const mongooseTypeToZod = (schemaPath: MongooseSchemaPath): ZodType => {
33
- const instance = schemaPath.instance;
34
-
35
- switch (instance) {
36
- case "String":
37
- if (schemaPath.enumValues?.length) {
38
- const values = schemaPath.enumValues as string[];
39
- return z.enum(values as [string, ...string[]]);
40
- }
41
- return z.string();
42
- case "Number":
43
- return z.number();
44
- case "Boolean":
45
- return z.boolean();
46
- case "Date":
47
- return z.string().describe("ISO 8601 date string");
48
- case "ObjectId":
49
- case "ObjectID":
50
- return z
51
- .string()
52
- .describe(
53
- schemaPath.options?.ref ? `ObjectId reference to ${schemaPath.options.ref}` : "ObjectId"
54
- );
55
- case "Array": {
56
- if (schemaPath.schema) {
57
- // Array of subdocuments
58
- return z.array(z.record(z.string(), z.any())).describe("Array of subdocuments");
59
- }
60
- // Array of primitives
61
- const caster = schemaPath.caster;
62
- if (caster) {
63
- const innerType = mongooseTypeToZod({
64
- instance: caster.instance,
65
- options: caster.options,
66
- });
67
- return z.array(innerType);
68
- }
69
- return z.array(z.any());
70
- }
71
- case "Mixed":
72
- case "Map":
73
- return z.record(z.string(), z.any());
74
- case "Embedded":
75
- return z.record(z.string(), z.any()).describe("Embedded document");
76
- default:
77
- return z.any();
78
- }
79
- };
80
-
81
23
  export const isFieldExcluded = (fieldPath: string, excludeFields: string[]): boolean => {
82
24
  return excludeFields.some((excluded) => {
83
25
  if (fieldPath === excluded) {
84
26
  return true;
85
27
  }
86
- // Support dot-notation parent matching: excluding "metadata" excludes "metadata.secretKey"
87
28
  if (fieldPath.startsWith(`${excluded}.`)) {
88
29
  return true;
89
30
  }
@@ -91,10 +32,6 @@ export const isFieldExcluded = (fieldPath: string, excludeFields: string[]): boo
91
32
  });
92
33
  };
93
34
 
94
- /**
95
- * REST write denylist from `validation.excludeFromCreate` / `excludeFromUpdate`.
96
- * MCP create/update must apply the same keys REST strips in `validateModelRequestBody`.
97
- */
98
35
  export const restWriteExcludeFields = (method: MCPMethod, validation: unknown): string[] => {
99
36
  if (typeof validation !== "object" || validation === null) {
100
37
  return [];
@@ -112,44 +49,35 @@ export const restWriteExcludeFields = (method: MCPMethod, validation: unknown):
112
49
  return [];
113
50
  };
114
51
 
115
- /** MCP `excludeFields` plus REST write denylist — used for tool schemas and persist. */
116
52
  export const writeExcludeFields = (config: MCPConfig, restExcludeFields: string[]): string[] => {
117
53
  return [...(config.excludeFields ?? []), ...restExcludeFields];
118
54
  };
119
55
 
120
- const getModelFields = (
121
- // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
122
- // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
123
- model: Model<any>,
124
- excludeFields: string[]
125
- ): ModelField[] => {
56
+ const getModelFields = <T>(model: Model<T>, excludeFields: string[]): ModelField[] => {
57
+ const description = describeModel(model);
126
58
  const fields: ModelField[] = [];
127
- const schemaPaths = model.schema.paths;
128
59
 
129
- for (const [path, rawSchemaPath] of Object.entries(schemaPaths)) {
130
- if (SYSTEM_FIELDS.has(path)) {
60
+ for (const [path, field] of Object.entries(description.fields)) {
61
+ if (SYSTEM_FIELD_PATHS.has(path) || field.system) {
131
62
  continue;
132
63
  }
133
64
  if (isFieldExcluded(path, excludeFields)) {
134
65
  continue;
135
66
  }
136
67
 
137
- const schemaPath = rawSchemaPath as unknown as MongooseSchemaPath;
138
68
  fields.push({
139
- description: schemaPath.options?.description,
69
+ description: field.description,
70
+ field,
140
71
  path,
141
- required: Boolean(schemaPath.isRequired),
142
- schemaPath,
72
+ required: field.required,
143
73
  });
144
74
  }
145
75
 
146
76
  return fields;
147
77
  };
148
78
 
149
- export const generateInputSchema = (
150
- // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
151
- // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
152
- model: Model<any>,
79
+ export const generateInputSchema = <T>(
80
+ model: Model<T>,
153
81
  method: MCPMethod,
154
82
  config: MCPConfig,
155
83
  queryFields?: string[],
@@ -158,8 +86,6 @@ export const generateInputSchema = (
158
86
  ): ZodType => {
159
87
  const excludeFields = writeExcludeFields(config, restExcludeFields);
160
88
  const populatable = (populatePaths ?? []).map((populatePath) => populatePath.path);
161
- // Only the model router's declared paths can be populated, so omit the parameter
162
- // entirely when there are none rather than inviting a request that must be refused.
163
89
  const populateParam = populatable.length
164
90
  ? z
165
91
  .string()
@@ -171,12 +97,9 @@ export const generateInputSchema = (
171
97
  case "create": {
172
98
  const fields = getModelFields(model, excludeFields);
173
99
  const shape: Record<string, ZodType> = {};
174
- for (const field of fields) {
175
- let zodType = mongooseTypeToZod(field.schemaPath);
176
- if (field.description) {
177
- zodType = zodType.describe(field.description);
178
- }
179
- shape[field.path] = field.required ? zodType : zodType.optional();
100
+ for (const {field, path, required} of fields) {
101
+ const zodType = fieldDescriptionToZodType(field, z);
102
+ shape[path] = required ? zodType : zodType.optional();
180
103
  }
181
104
  return z.object(shape);
182
105
  }
@@ -186,12 +109,8 @@ export const generateInputSchema = (
186
109
  const shape: Record<string, ZodType> = {
187
110
  id: z.string().describe("Document ID to update"),
188
111
  };
189
- for (const field of fields) {
190
- let zodType = mongooseTypeToZod(field.schemaPath);
191
- if (field.description) {
192
- zodType = zodType.describe(field.description);
193
- }
194
- shape[field.path] = zodType.optional();
112
+ for (const {field, path} of fields) {
113
+ shape[path] = fieldDescriptionToZodType(field, z).optional();
195
114
  }
196
115
  return z.object(shape);
197
116
  }
@@ -218,7 +137,6 @@ export const generateInputSchema = (
218
137
  if (populateParam) {
219
138
  shape.populate = populateParam;
220
139
  }
221
- // Add queryFields as optional filter parameters
222
140
  const filterableFields = (queryFields ?? []).filter(
223
141
  (field) => !isFieldExcluded(field, excludeFields)
224
142
  );
@@ -254,37 +172,39 @@ export const generateInputSchema = (
254
172
  }
255
173
  };
256
174
 
257
- const describeField = (field: ModelField): string => {
258
- const parts = [field.path];
259
- const instance = field.schemaPath.instance;
260
-
261
- // Type info
262
- if (instance === "ObjectId" || instance === "ObjectID") {
263
- const ref = field.schemaPath.options?.ref;
264
- parts.push(ref ? `(ref: ${ref})` : "(ObjectId)");
265
- } else if (instance === "Array") {
266
- if (field.schemaPath.caster?.instance) {
267
- parts.push(`(${field.schemaPath.caster.instance}[])`);
268
- } else {
269
- parts.push("(Array)");
175
+ const describeFieldKind = (field: FieldDescription): string => {
176
+ if (field.isArray) {
177
+ if (field.item?.kind) {
178
+ const itemLabel =
179
+ field.item.kind === "objectId"
180
+ ? field.item.ref
181
+ ? `ref:${field.item.ref}`
182
+ : "ObjectId"
183
+ : field.item.kind.charAt(0).toUpperCase() + field.item.kind.slice(1);
184
+ return `(${itemLabel}[])`;
270
185
  }
271
- } else if (instance === "String" && field.schemaPath.enumValues?.length) {
272
- parts.push(`(enum: ${field.schemaPath.enumValues.join("|")})`);
273
- } else {
274
- parts.push(`(${instance})`);
186
+ return "(Array)";
187
+ }
188
+ if (field.kind === "objectId") {
189
+ return field.ref ? `(ref: ${field.ref})` : "(ObjectId)";
190
+ }
191
+ if (field.kind === "string" && field.enum?.length) {
192
+ return `(enum: ${field.enum.join("|")})`;
275
193
  }
194
+ const label = field.kind.charAt(0).toUpperCase() + field.kind.slice(1);
195
+ return `(${label})`;
196
+ };
276
197
 
277
- if (field.required) {
198
+ const describeField = ({field, path, required}: ModelField): string => {
199
+ const parts = [path, describeFieldKind(field)];
200
+ if (required) {
278
201
  parts.push("required");
279
202
  }
280
-
281
203
  return parts.join(" ");
282
204
  };
283
205
 
284
- export const generateToolDescription = (
285
- // noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
286
- // biome-ignore lint/suspicious/noExplicitAny: Mongoose's invariant generics require any to accept arbitrary consumer models
287
- model: Model<any>,
206
+ export const generateToolDescription = <T>(
207
+ model: Model<T>,
288
208
  method: MCPMethod,
289
209
  config: MCPConfig,
290
210
  queryFields?: string[],
@@ -315,15 +235,13 @@ export const generateToolDescription = (
315
235
  }
316
236
  case "read": {
317
237
  const parts = [`Read a single ${modelName} by ID.`];
318
- // Only the model router's declared paths can be populated, so advertising every ref
319
- // field would point the model at requests that are refused.
320
238
  const fields = getModelFields(model, excludeFields);
321
239
  const refFields = (populatePaths ?? [])
322
240
  .map((populatePath) => fields.find((field) => field.path === populatePath.path))
323
- .filter((field): field is ModelField => Boolean(field?.schemaPath.options?.ref));
241
+ .filter((field): field is ModelField => Boolean(field?.field.ref));
324
242
  if (refFields.length) {
325
243
  parts.push(
326
- `Populate-able refs: ${refFields.map((f) => `${f.path} (${f.schemaPath.options?.ref})`).join(", ")}.`
244
+ `Populate-able refs: ${refFields.map((f) => `${f.path} (${f.field.ref})`).join(", ")}.`
327
245
  );
328
246
  }
329
247
  return parts.join(" ");
package/src/mcp/server.ts CHANGED
@@ -12,6 +12,7 @@ import {getAllMCPTools, type MCPToolDefinition} from "./toolGenerator";
12
12
  export interface MCPServerOptions {
13
13
  userModel: UserModel;
14
14
  betterAuth?: BetterAuthInstance;
15
+ mcpServiceTokens?: boolean;
15
16
  }
16
17
 
17
18
  export const mountMCPServer = (app: Application, options: MCPServerOptions): void => {
@@ -21,6 +22,7 @@ export const mountMCPServer = (app: Application, options: MCPServerOptions): voi
21
22
  }
22
23
  const authContext: MCPAuthContext = {
23
24
  betterAuth: options.betterAuth,
25
+ mcpServiceTokens: options.mcpServiceTokens,
24
26
  userModel: options.userModel,
25
27
  };
26
28
 
@@ -0,0 +1,330 @@
1
+ import {afterEach, beforeEach, describe, it} from "bun:test";
2
+ import {assert} from "chai";
3
+ import type express from "express";
4
+ import {DateTime} from "luxon";
5
+ import mongoose from "mongoose";
6
+ import supertest from "supertest";
7
+ import type TestAgent from "supertest/lib/agent";
8
+
9
+ import {type UserModel as AuthUserModel, addAuthRoutes, setupAuth} from "../auth";
10
+ import {apiErrorMiddleware, apiUnauthorizedMiddleware} from "../errors";
11
+ import {McpServiceToken} from "../models/mcpServiceToken";
12
+ import {TerrenoApp} from "../terrenoApp";
13
+ import {authAsUser, getBaseServer, setupDb, UserModel} from "../tests";
14
+ import {addMcpServiceTokenRoutes, MAX_ACTIVE_MCP_SERVICE_TOKENS} from "./serviceTokens";
15
+
16
+ const PUBLIC_MCP_URL = "https://api.example.com";
17
+
18
+ const assertNoSecrets = (body: unknown): void => {
19
+ const serialized = JSON.stringify(body);
20
+ assert.notInclude(serialized, "tokenHash");
21
+ if (typeof body === "object" && body !== null && "data" in body) {
22
+ const data = (body as {data: unknown}).data;
23
+ if (Array.isArray(data)) {
24
+ for (const item of data) {
25
+ assert.notProperty(item, "token");
26
+ assert.notProperty(item, "tokenHash");
27
+ }
28
+ }
29
+ }
30
+ };
31
+
32
+ describe("MCP service token routes", () => {
33
+ let app: express.Application;
34
+ let agent: TestAgent;
35
+ let adminAgent: TestAgent;
36
+ let notAdminId: mongoose.Types.ObjectId;
37
+
38
+ beforeEach(async () => {
39
+ const users = await setupDb();
40
+ notAdminId = users[1]._id as mongoose.Types.ObjectId;
41
+ await McpServiceToken.deleteMany({});
42
+
43
+ app = getBaseServer();
44
+ setupAuth(app, UserModel as never);
45
+ addAuthRoutes(app, UserModel as never);
46
+ addMcpServiceTokenRoutes(app, {publicMcpUrl: PUBLIC_MCP_URL});
47
+ app.use(apiUnauthorizedMiddleware);
48
+ app.use(apiErrorMiddleware);
49
+
50
+ agent = await authAsUser(app, "notAdmin");
51
+ adminAgent = await authAsUser(app, "admin");
52
+ });
53
+
54
+ it("creates a token once and returns mcpUrl with the plaintext", async () => {
55
+ const res = await agent.post("/mcp/service-tokens").send({name: "Perplexity laptop"});
56
+
57
+ assert.equal(res.status, 200);
58
+ assert.match(res.body.data.token, /^mcp_[0-9a-f]{64}$/);
59
+ assert.equal(res.body.data.name, "Perplexity laptop");
60
+ assert.equal(res.body.data.mcpUrl, `${PUBLIC_MCP_URL}/mcp`);
61
+ assert.equal(res.body.data.tokenPrefix, res.body.data.token.slice(4, 12));
62
+ assert.isUndefined(res.body.data.tokenHash);
63
+
64
+ const stored = await McpServiceToken.findExactlyOne({_id: res.body.data.id});
65
+ assert.notEqual(stored.tokenHash, res.body.data.token);
66
+ assert.notInclude(JSON.stringify(stored.toJSON()), res.body.data.token);
67
+ });
68
+
69
+ it("lists only the caller's tokens without plaintext or hash", async () => {
70
+ const mine = await agent.post("/mcp/service-tokens").send({name: "Mine"});
71
+ await adminAgent.post("/mcp/service-tokens").send({name: "Admin token"});
72
+
73
+ const res = await agent.get("/mcp/service-tokens");
74
+
75
+ assert.equal(res.status, 200);
76
+ assert.equal(res.body.total, 1);
77
+ assert.equal(res.body.page, 1);
78
+ assert.equal(res.body.more, false);
79
+ assert.equal(res.body.data.length, 1);
80
+ assert.equal(res.body.data[0].id, mine.body.data.id);
81
+ assert.equal(res.body.data[0].name, "Mine");
82
+ assertNoSecrets(res.body);
83
+ });
84
+
85
+ it("accepts an optional future ISO expiresAt on create", async () => {
86
+ const expiresAt = DateTime.now().plus({day: 1}).toUTC().toISO();
87
+ const res = await agent.post("/mcp/service-tokens").send({
88
+ expiresAt,
89
+ name: "Expiring",
90
+ });
91
+
92
+ assert.equal(res.status, 200);
93
+ assert.equal(DateTime.fromISO(res.body.data.expiresAt).toUTC().toISO(), expiresAt);
94
+ });
95
+
96
+ it("revokes an owned token and hides it from other users", async () => {
97
+ const created = await agent.post("/mcp/service-tokens").send({name: "To revoke"});
98
+ const tokenId = created.body.data.id as string;
99
+
100
+ const otherDelete = await adminAgent.delete(`/mcp/service-tokens/${tokenId}`);
101
+ assert.equal(otherDelete.status, 404);
102
+
103
+ const revoked = await agent.delete(`/mcp/service-tokens/${tokenId}`);
104
+ assert.equal(revoked.status, 200);
105
+ assert.equal(revoked.body.data.id, tokenId);
106
+ assert.isString(revoked.body.data.revokedAt);
107
+
108
+ const listed = await agent.get("/mcp/service-tokens");
109
+ assert.equal(listed.body.data[0].id, tokenId);
110
+ assert.isString(listed.body.data[0].revokedAt);
111
+
112
+ const again = await agent.delete(`/mcp/service-tokens/${tokenId}`);
113
+ assert.equal(again.status, 404);
114
+ });
115
+
116
+ it("rejects a create once the caller already has 10 active tokens", async () => {
117
+ for (let index = 0; index < MAX_ACTIVE_MCP_SERVICE_TOKENS; index += 1) {
118
+ await McpServiceToken.issueFor({_id: notAdminId}, {name: `Token ${index}`});
119
+ }
120
+
121
+ const res = await agent.post("/mcp/service-tokens").send({name: "One too many"});
122
+
123
+ assert.equal(res.status, 400);
124
+ assert.match(res.body.title, /Maximum of 10 active MCP service tokens/);
125
+ assert.equal(await McpServiceToken.countActiveForUser(notAdminId), 10);
126
+ });
127
+
128
+ it("rejects mcp_ bearer tokens on self-serve routes", async () => {
129
+ const created = await agent.post("/mcp/service-tokens").send({name: "Connector"});
130
+ const mcpToken = created.body.data.token as string;
131
+
132
+ const listed = await supertest(app)
133
+ .get("/mcp/service-tokens")
134
+ .set("Authorization", `Bearer ${mcpToken}`);
135
+ const minted = await supertest(app)
136
+ .post("/mcp/service-tokens")
137
+ .set("Authorization", `Bearer ${mcpToken}`)
138
+ .send({name: "Nested"});
139
+ const revoked = await supertest(app)
140
+ .delete(`/mcp/service-tokens/${created.body.data.id}`)
141
+ .set("Authorization", `Bearer ${mcpToken}`);
142
+
143
+ assert.equal(listed.status, 401);
144
+ assert.equal(minted.status, 401);
145
+ assert.equal(revoked.status, 401);
146
+ });
147
+
148
+ it("requires a session or JWT", async () => {
149
+ const res = await supertest(app).get("/mcp/service-tokens");
150
+ assert.equal(res.status, 401);
151
+ });
152
+
153
+ it("returns 404 for an unknown token id", async () => {
154
+ const res = await agent.delete(
155
+ `/mcp/service-tokens/${new mongoose.Types.ObjectId().toString()}`
156
+ );
157
+ assert.equal(res.status, 404);
158
+ });
159
+
160
+ it("returns 404 for a malformed token id", async () => {
161
+ const res = await agent.delete("/mcp/service-tokens/not-an-object-id");
162
+ assert.equal(res.status, 404);
163
+ });
164
+
165
+ it("rejects a raw mcp_ authorization header without the Bearer prefix", async () => {
166
+ const created = await agent.post("/mcp/service-tokens").send({name: "Raw"});
167
+ const mcpToken = created.body.data.token as string;
168
+
169
+ const res = await supertest(app).get("/mcp/service-tokens").set("Authorization", mcpToken);
170
+ assert.equal(res.status, 401);
171
+ });
172
+
173
+ it("rejects a missing, non-string, or blank name", async () => {
174
+ const missing = await agent.post("/mcp/service-tokens").send({});
175
+ const nonString = await agent.post("/mcp/service-tokens").send({name: 42});
176
+ const blank = await agent.post("/mcp/service-tokens").send({name: " "});
177
+
178
+ for (const res of [missing, nonString, blank]) {
179
+ assert.equal(res.status, 400);
180
+ assert.equal(res.body.title, "name is required");
181
+ }
182
+ });
183
+
184
+ it("trims the name and treats an empty expiresAt as unset", async () => {
185
+ const res = await agent.post("/mcp/service-tokens").send({expiresAt: "", name: " Padded "});
186
+
187
+ assert.equal(res.status, 200);
188
+ assert.equal(res.body.data.name, "Padded");
189
+ assert.notOk(res.body.data.expiresAt);
190
+ });
191
+
192
+ it("rejects non-string, invalid, and past expiresAt values", async () => {
193
+ const nonString = await agent.post("/mcp/service-tokens").send({expiresAt: 123, name: "A"});
194
+ const invalid = await agent
195
+ .post("/mcp/service-tokens")
196
+ .send({expiresAt: "not-a-date", name: "B"});
197
+ const past = await agent.post("/mcp/service-tokens").send({
198
+ expiresAt: DateTime.now().minus({day: 1}).toUTC().toISO(),
199
+ name: "C",
200
+ });
201
+
202
+ assert.equal(nonString.status, 400);
203
+ assert.equal(nonString.body.title, "expiresAt must be an ISO-8601 datetime string");
204
+ assert.equal(invalid.status, 400);
205
+ assert.equal(invalid.body.title, "expiresAt must be an ISO-8601 datetime string");
206
+ assert.equal(past.status, 400);
207
+ assert.equal(past.body.title, "expiresAt must be in the future");
208
+ });
209
+
210
+ it("validates and applies page and limit on list", async () => {
211
+ for (const name of ["One", "Two", "Three"]) {
212
+ await agent.post("/mcp/service-tokens").send({name});
213
+ }
214
+
215
+ const badPage = await agent.get("/mcp/service-tokens?page=0");
216
+ assert.equal(badPage.status, 400);
217
+ assert.equal(badPage.body.title, "Invalid page");
218
+
219
+ const fractionalPage = await agent.get("/mcp/service-tokens?page=1.5");
220
+ assert.equal(fractionalPage.status, 400);
221
+
222
+ const badLimit = await agent.get("/mcp/service-tokens?limit=abc");
223
+ assert.equal(badLimit.status, 400);
224
+ assert.equal(badLimit.body.title, "Invalid limit");
225
+
226
+ const zeroLimit = await agent.get("/mcp/service-tokens?limit=0");
227
+ assert.equal(zeroLimit.status, 400);
228
+
229
+ const paged = await agent.get("/mcp/service-tokens?page=2&limit=2");
230
+ assert.equal(paged.status, 200);
231
+ assert.equal(paged.body.page, 2);
232
+ assert.equal(paged.body.limit, 2);
233
+ assert.equal(paged.body.total, 3);
234
+ assert.equal(paged.body.data.length, 1);
235
+ assert.equal(paged.body.more, false);
236
+
237
+ const capped = await agent.get("/mcp/service-tokens?limit=10000");
238
+ assert.equal(capped.status, 200);
239
+ assert.isBelow(capped.body.limit, 10000);
240
+ });
241
+ });
242
+
243
+ describe("MCP service token mcpUrl resolution", () => {
244
+ const buildApp = (publicMcpUrl?: string): express.Application => {
245
+ const app = getBaseServer();
246
+ setupAuth(app, UserModel as never);
247
+ addAuthRoutes(app, UserModel as never);
248
+ addMcpServiceTokenRoutes(app, {publicMcpUrl});
249
+ app.use(apiUnauthorizedMiddleware);
250
+ app.use(apiErrorMiddleware);
251
+ return app;
252
+ };
253
+
254
+ const originalBetterAuthUrl = process.env.BETTER_AUTH_URL;
255
+
256
+ beforeEach(async () => {
257
+ await setupDb();
258
+ await McpServiceToken.deleteMany({});
259
+ });
260
+
261
+ afterEach(() => {
262
+ if (originalBetterAuthUrl === undefined) {
263
+ delete process.env.BETTER_AUTH_URL;
264
+ } else {
265
+ process.env.BETTER_AUTH_URL = originalBetterAuthUrl;
266
+ }
267
+ });
268
+
269
+ it("keeps a configured URL that already ends in /mcp and strips a trailing slash", async () => {
270
+ const app = buildApp("https://api.example.com/mcp/");
271
+ const agent = await authAsUser(app, "notAdmin");
272
+
273
+ const res = await agent.post("/mcp/service-tokens").send({name: "Configured"});
274
+
275
+ assert.equal(res.status, 200);
276
+ assert.equal(res.body.data.mcpUrl, "https://api.example.com/mcp");
277
+ });
278
+
279
+ it("falls back to BETTER_AUTH_URL when no publicMcpUrl is configured", async () => {
280
+ process.env.BETTER_AUTH_URL = "https://auth.example.com";
281
+ const app = buildApp();
282
+ const agent = await authAsUser(app, "notAdmin");
283
+
284
+ const res = await agent.post("/mcp/service-tokens").send({name: "Env"});
285
+
286
+ assert.equal(res.status, 200);
287
+ assert.equal(res.body.data.mcpUrl, "https://auth.example.com/mcp");
288
+ });
289
+
290
+ it("derives the URL from the request host when nothing is configured", async () => {
291
+ delete process.env.BETTER_AUTH_URL;
292
+ const app = buildApp();
293
+ const agent = await authAsUser(app, "notAdmin");
294
+
295
+ const res = await agent.post("/mcp/service-tokens").send({name: "Host"});
296
+
297
+ assert.equal(res.status, 200);
298
+ assert.match(res.body.data.mcpUrl, /^http:\/\/127\.0\.0\.1:\d+\/mcp$/);
299
+ });
300
+ });
301
+
302
+ describe("MCP service token OpenAPI", () => {
303
+ it("documents create, list, and revoke on /openapi.json", async () => {
304
+ const app = new TerrenoApp({
305
+ configureApp: (router, options) => {
306
+ addMcpServiceTokenRoutes(router, {
307
+ openApi: options?.openApi,
308
+ publicMcpUrl: PUBLIC_MCP_URL,
309
+ });
310
+ },
311
+ skipListen: true,
312
+ userModel: UserModel as unknown as AuthUserModel,
313
+ }).build();
314
+
315
+ const res = await supertest(app).get("/openapi.json");
316
+
317
+ assert.equal(res.status, 200);
318
+ assert.equal(res.body.paths["/mcp/service-tokens"].post.operationId, "createMcpServiceToken");
319
+ assert.equal(res.body.paths["/mcp/service-tokens"].get.operationId, "listMcpServiceTokens");
320
+ assert.equal(
321
+ res.body.paths["/mcp/service-tokens/{id}"].delete.operationId,
322
+ "revokeMcpServiceToken"
323
+ );
324
+ assert.equal(
325
+ res.body.paths["/mcp/service-tokens"].post.responses["200"].content["application/json"].schema
326
+ .properties.data.type,
327
+ "object"
328
+ );
329
+ });
330
+ });