@terreno/api 57.16.2 → 57.18.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 (184) hide show
  1. package/dist/actions.d.ts +26 -3
  2. package/dist/actions.js +102 -16
  3. package/dist/api.d.ts +7 -0
  4. package/dist/api.js +59 -3
  5. package/dist/auth.d.ts +28 -4
  6. package/dist/auth.js +140 -15
  7. package/dist/authRecovery.d.ts +31 -0
  8. package/dist/authRecovery.js +86 -6
  9. package/dist/betterAuth.d.ts +86 -0
  10. package/dist/betterAuthApp.d.ts +17 -0
  11. package/dist/betterAuthApp.js +12 -1
  12. package/dist/betterAuthOAuthHandoff.d.ts +24 -0
  13. package/dist/betterAuthOAuthHandoff.js +305 -0
  14. package/dist/betterAuthSetup.d.ts +37 -2
  15. package/dist/betterAuthSetup.js +304 -24
  16. package/dist/expressServer.d.ts +16 -0
  17. package/dist/expressServer.js +61 -14
  18. package/dist/githubAuth.d.ts +9 -0
  19. package/dist/githubAuth.js +230 -31
  20. package/dist/index.d.ts +9 -1
  21. package/dist/index.js +27 -3
  22. package/dist/mcp/actionTools.d.ts +4 -0
  23. package/dist/mcp/actionTools.js +158 -0
  24. package/dist/mcp/auth.d.ts +30 -0
  25. package/dist/mcp/auth.js +83 -28
  26. package/dist/mcp/createMCPRequest.d.ts +5 -1
  27. package/dist/mcp/createMCPRequest.js +3 -3
  28. package/dist/mcp/handlers.d.ts +3 -0
  29. package/dist/mcp/handlers.js +43 -27
  30. package/dist/mcp/oauth.d.ts +14 -0
  31. package/dist/mcp/oauth.js +618 -0
  32. package/dist/mcp/oauthMetadata.d.ts +89 -0
  33. package/dist/mcp/oauthMetadata.js +137 -0
  34. package/dist/mcp/registry.d.ts +5 -0
  35. package/dist/mcp/registry.js +9 -1
  36. package/dist/mcp/server.d.ts +6 -0
  37. package/dist/mcp/server.js +44 -7
  38. package/dist/mcp/serviceTokens.js +12 -2
  39. package/dist/mcp/toolExecution.d.ts +12 -0
  40. package/dist/mcp/toolExecution.js +60 -0
  41. package/dist/mcp/toolGenerator.d.ts +4 -1
  42. package/dist/mcp/toolGenerator.js +26 -60
  43. package/dist/mcp/types.d.ts +4 -4
  44. package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
  45. package/dist/models/mcpOAuthAuthorization.js +86 -0
  46. package/dist/models/mcpOAuthClient.d.ts +2 -0
  47. package/dist/models/mcpOAuthClient.js +42 -0
  48. package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
  49. package/dist/models/mcpOAuthRevokedFamily.js +36 -0
  50. package/dist/models/mcpOAuthToken.d.ts +12 -0
  51. package/dist/models/mcpOAuthToken.js +159 -0
  52. package/dist/models/mcpServiceToken.d.ts +1 -0
  53. package/dist/models/mcpServiceToken.js +21 -4
  54. package/dist/permissions.d.ts +7 -0
  55. package/dist/permissions.js +18 -1
  56. package/dist/rateLimit/policies.d.ts +4 -0
  57. package/dist/rateLimit/policies.js +46 -7
  58. package/dist/rbac/access.js +1 -0
  59. package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
  60. package/dist/rbac/membershipOrgAdminSource.js +5 -0
  61. package/dist/rbac/modelRouterAccess.d.ts +7 -1
  62. package/dist/rbac/modelRouterAccess.js +37 -24
  63. package/dist/rbac/realtimeAccess.js +17 -3
  64. package/dist/rbac/resolve.js +66 -9
  65. package/dist/rbac/roleManager.js +60 -5
  66. package/dist/rbac/roleModel.js +1 -1
  67. package/dist/rbac/statements.d.ts +1 -1
  68. package/dist/rbac/statements.js +13 -1
  69. package/dist/rbac/types.d.ts +12 -0
  70. package/dist/rbac/userWriteGuards.d.ts +50 -0
  71. package/dist/rbac/userWriteGuards.js +156 -0
  72. package/dist/realtime/changeStreamWatcher.d.ts +4 -1
  73. package/dist/realtime/changeStreamWatcher.js +157 -73
  74. package/dist/realtime/queryMatcher.d.ts +3 -0
  75. package/dist/realtime/queryMatcher.js +25 -10
  76. package/dist/realtime/realtimeApp.d.ts +16 -1
  77. package/dist/realtime/realtimeApp.js +76 -8
  78. package/dist/realtime/socketAuth.d.ts +17 -6
  79. package/dist/realtime/socketAuth.js +77 -16
  80. package/dist/realtime/types.d.ts +8 -5
  81. package/dist/requestContext.d.ts +22 -0
  82. package/dist/requestContext.js +22 -1
  83. package/dist/seedRunner.js +3 -1
  84. package/dist/sortFields.d.ts +33 -0
  85. package/dist/sortFields.js +55 -0
  86. package/dist/sync/executors.js +140 -2
  87. package/dist/sync/models.d.ts +2 -0
  88. package/dist/sync/models.js +5 -0
  89. package/dist/sync/mutationHandler.js +70 -7
  90. package/dist/sync/routes.js +4 -2
  91. package/dist/sync/syncSeqPlugin.js +6 -5
  92. package/dist/terrenoApp.d.ts +14 -0
  93. package/dist/terrenoApp.js +21 -6
  94. package/dist/types/mcpOAuth.d.ts +101 -0
  95. package/dist/types/mcpOAuth.js +2 -0
  96. package/dist/types/mcpServiceToken.d.ts +8 -0
  97. package/package.json +3 -3
  98. package/src/actions.test.ts +118 -0
  99. package/src/actions.ts +139 -17
  100. package/src/api.arrayOperations.test.ts +78 -0
  101. package/src/api.test.ts +36 -0
  102. package/src/api.ts +76 -4
  103. package/src/auth.test.ts +521 -3
  104. package/src/auth.ts +171 -17
  105. package/src/authRecovery.test.ts +99 -0
  106. package/src/authRecovery.ts +117 -5
  107. package/src/authVerification.test.ts +3 -3
  108. package/src/betterAuth.ts +104 -1
  109. package/src/betterAuthApp.test.ts +634 -1
  110. package/src/betterAuthApp.ts +28 -0
  111. package/src/betterAuthOAuthHandoff.test.ts +946 -0
  112. package/src/betterAuthOAuthHandoff.ts +375 -0
  113. package/src/betterAuthSetup.test.ts +393 -4
  114. package/src/betterAuthSetup.ts +402 -29
  115. package/src/expressServer.test.ts +93 -0
  116. package/src/expressServer.ts +81 -14
  117. package/src/githubAuth.test.ts +448 -6
  118. package/src/githubAuth.ts +276 -34
  119. package/src/index.ts +35 -1
  120. package/src/mcp/actionTools.test.ts +498 -0
  121. package/src/mcp/actionTools.ts +220 -0
  122. package/src/mcp/auth.test.ts +114 -1
  123. package/src/mcp/auth.ts +122 -35
  124. package/src/mcp/createMCPRequest.ts +8 -2
  125. package/src/mcp/handlers.test.ts +27 -0
  126. package/src/mcp/handlers.ts +21 -6
  127. package/src/mcp/oauth.test.ts +1026 -0
  128. package/src/mcp/oauth.ts +798 -0
  129. package/src/mcp/oauthMetadata.ts +234 -0
  130. package/src/mcp/registry.ts +11 -0
  131. package/src/mcp/server.ts +54 -14
  132. package/src/mcp/serviceTokens.ts +16 -3
  133. package/src/mcp/toolExecution.ts +67 -0
  134. package/src/mcp/toolGenerator.ts +27 -83
  135. package/src/mcp/types.ts +4 -4
  136. package/src/models/mcpOAuthAuthorization.ts +97 -0
  137. package/src/models/mcpOAuthClient.ts +49 -0
  138. package/src/models/mcpOAuthRevokedFamily.ts +47 -0
  139. package/src/models/mcpOAuthToken.test.ts +82 -0
  140. package/src/models/mcpOAuthToken.ts +195 -0
  141. package/src/models/mcpServiceToken.ts +26 -2
  142. package/src/permissions.ts +17 -0
  143. package/src/rateLimit/policies.ts +54 -10
  144. package/src/rateLimit/rateLimit.test.ts +41 -0
  145. package/src/rbac/access.ts +1 -0
  146. package/src/rbac/membershipOrgAdminSource.ts +5 -0
  147. package/src/rbac/modelRouterAccess.ts +40 -23
  148. package/src/rbac/realtimeAccess.test.ts +43 -0
  149. package/src/rbac/realtimeAccess.ts +23 -3
  150. package/src/rbac/resolve.test.ts +179 -1
  151. package/src/rbac/resolve.ts +78 -9
  152. package/src/rbac/roleManager.test.ts +132 -0
  153. package/src/rbac/roleManager.ts +69 -5
  154. package/src/rbac/roleModel.ts +1 -1
  155. package/src/rbac/statements.ts +14 -1
  156. package/src/rbac/types.ts +12 -0
  157. package/src/rbac/userWriteGuards.test.ts +407 -0
  158. package/src/rbac/userWriteGuards.ts +185 -0
  159. package/src/realtime/changeStreamWatcher.ts +203 -75
  160. package/src/realtime/queryMatcher.ts +30 -13
  161. package/src/realtime/realtime.test.ts +132 -0
  162. package/src/realtime/realtimeApp.ts +94 -10
  163. package/src/realtime/realtimeAppSetup.test.ts +282 -1
  164. package/src/realtime/socketAuth.test.ts +140 -8
  165. package/src/realtime/socketAuth.ts +90 -19
  166. package/src/realtime/types.ts +8 -5
  167. package/src/requestContext.ts +52 -1
  168. package/src/requestCredential.test.ts +89 -0
  169. package/src/seedRunner.test.ts +21 -0
  170. package/src/seedRunner.ts +3 -1
  171. package/src/sortFields.ts +69 -0
  172. package/src/sync/executors.test.ts +382 -3
  173. package/src/sync/executors.ts +179 -4
  174. package/src/sync/models.ts +8 -0
  175. package/src/sync/mutationHandler.test.ts +166 -2
  176. package/src/sync/mutationHandler.ts +97 -5
  177. package/src/sync/routes.ts +4 -2
  178. package/src/sync/syncFrontier.test.ts +11 -0
  179. package/src/sync/syncPhaseC.test.ts +18 -0
  180. package/src/sync/syncSeqPlugin.ts +6 -5
  181. package/src/sync/syncSocket.test.ts +92 -0
  182. package/src/terrenoApp.ts +36 -21
  183. package/src/types/mcpOAuth.ts +129 -0
  184. package/src/types/mcpServiceToken.ts +6 -1
package/src/actions.ts CHANGED
@@ -10,7 +10,9 @@ import {APIError, ForbiddenError, ValidationError} from "./errors";
10
10
  import {defaultOpenApiErrorResponses} from "./openApi";
11
11
  import {checkPermissions, type PermissionMethod} from "./permissions";
12
12
  import {createIsPermitted} from "./rbac/middleware";
13
+ import {buildAccessScopeCheck} from "./rbac/modelRouterAccess";
13
14
  import type {AnyTerrenoAccess, ModelRouterAccessOptions} from "./rbac/types";
15
+ import {assertCanWriteTargetUser, assertCanWriteUserIdentity} from "./rbac/userWriteGuards";
14
16
 
15
17
  // At least two characters: leading letter plus one or more alphanumeric/_/- chars.
16
18
  export const ACTION_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]+$/;
@@ -24,7 +26,18 @@ export interface ActionContext<TDoc, TBody, TQuery> {
24
26
  doc: TDoc;
25
27
  }
26
28
 
27
- interface BaseActionConfig<TBody, TQuery, TResponse> {
29
+ /** Exposes an action as an MCP tool on `/mcp`. */
30
+ export interface ActionMCPConfig {
31
+ /** MCP tool name, unique across every tool the app exposes (e.g. `todos_bulk_complete`). */
32
+ name: string;
33
+ /** Tool description shown to the model. Defaults to the action's description or summary. */
34
+ description?: string;
35
+ }
36
+
37
+ // MCP tool names: letters, digits, underscore, dot, and hyphen, up to 64 characters.
38
+ const MCP_TOOL_NAME_PATTERN = /^[A-Za-z0-9_.-]{1,64}$/;
39
+
40
+ export interface BaseActionConfig<TBody, TQuery, TResponse> {
28
41
  method: "GET" | "POST";
29
42
  allowAnonymous?: boolean;
30
43
  permissions?: PermissionMethod<unknown>[];
@@ -36,6 +49,21 @@ interface BaseActionConfig<TBody, TQuery, TResponse> {
36
49
  description?: string;
37
50
  tag?: string;
38
51
  status?: number;
52
+ /**
53
+ * Also register the action as an MCP tool. The tool runs the same permission chain
54
+ * (including RBAC `access`) and the same zod validation as REST. Its input is `{id, ...body}`
55
+ * for an instance POST action, `{id, ...query}` for an instance GET action, and the body or
56
+ * query alone for a collection action. The handler gets an MCP request
57
+ * (`req.isMCPRequest === true`) and a `res` that throws if touched, so actions that write to
58
+ * `res` directly cannot opt in.
59
+ */
60
+ mcp?: ActionMCPConfig;
61
+ /**
62
+ * REST only. Send the handler's return value as the response body (with `status`) instead
63
+ * of wrapping it as `{data: …}`. Use it to keep an existing route's response contract when
64
+ * converting it to an action. An `undefined` return sends an empty body.
65
+ */
66
+ unwrapResponse?: boolean;
39
67
  }
40
68
 
41
69
  export interface InstanceActionConfig<TDoc, TBody, TQuery, TResponse>
@@ -62,7 +90,7 @@ export const defineCollectionAction = <TBody = unknown, TQuery = unknown, TRespo
62
90
  return config;
63
91
  };
64
92
 
65
- type ActionScope = "instance" | "collection";
93
+ export type ActionScope = "instance" | "collection";
66
94
 
67
95
  type RegisteredAction<T> =
68
96
  | {scope: "instance"; name: string; config: InstanceActionConfig<T, unknown, unknown, unknown>}
@@ -113,7 +141,21 @@ export const runActionPermissions = async <T>(
113
141
  const rbacCheck = isPermitted({
114
142
  [rbacAccess.resource]: [rbacAccess.action],
115
143
  }) as PermissionMethod<unknown>;
116
- permissions = [...(action.permissions ?? []), rbacCheck];
144
+ // Same resource as the router: its per-document `access.scope` and `access.also` apply to
145
+ // the action exactly as they do to the mapped CRUD method.
146
+ const routerChecks: PermissionMethod<unknown>[] = [];
147
+ if (routerAccess && routerAccess.resource === rbacAccess.resource) {
148
+ const scopeCheck = buildAccessScopeCheck<unknown>(
149
+ accessControl,
150
+ routerAccess,
151
+ rbacAccess.action
152
+ );
153
+ if (scopeCheck) {
154
+ routerChecks.push(scopeCheck);
155
+ }
156
+ routerChecks.push(...((routerAccess.also?.[method] ?? []) as PermissionMethod<unknown>[]));
157
+ }
158
+ permissions = [...(action.permissions ?? []), rbacCheck, ...routerChecks];
117
159
  }
118
160
  if (!permissions) {
119
161
  throw new APIError({status: 500, title: "Action missing permissions configuration"});
@@ -208,7 +250,16 @@ export const wrapActionResponse = (
208
250
  if (res.headersSent) {
209
251
  return;
210
252
  }
211
- res.status(action.status ?? 200).json({data: handlerResult ?? null});
253
+ const status = action.status ?? 200;
254
+ if (!action.unwrapResponse) {
255
+ res.status(status).json({data: handlerResult ?? null});
256
+ return;
257
+ }
258
+ if (handlerResult === undefined) {
259
+ res.status(status).end();
260
+ return;
261
+ }
262
+ res.status(status).json(handlerResult);
212
263
  };
213
264
 
214
265
  let inlineOpenApiSchemaCounter = 0;
@@ -282,20 +333,24 @@ export const createActionOpenApiMiddleware = <T>({
282
333
  [statusCode]: {
283
334
  content: {
284
335
  "application/json": {
285
- schema: action.response
286
- ? {
287
- properties: {
288
- data: zodToJsonSchema(action.response),
289
- },
290
- required: ["data"],
291
- type: "object",
292
- }
293
- : {
294
- properties: {
295
- data: {type: "object"},
336
+ schema: action.unwrapResponse
337
+ ? action.response
338
+ ? zodToJsonSchema(action.response)
339
+ : {type: "object"}
340
+ : action.response
341
+ ? {
342
+ properties: {
343
+ data: zodToJsonSchema(action.response),
344
+ },
345
+ required: ["data"],
346
+ type: "object",
347
+ }
348
+ : {
349
+ properties: {
350
+ data: {type: "object"},
351
+ },
352
+ type: "object",
296
353
  },
297
- type: "object",
298
- },
299
354
  },
300
355
  },
301
356
  description: "Successful response",
@@ -358,6 +413,47 @@ const validateActionConfig = (
358
413
  title: `Action "${name}" (${scope}) only supports GET and POST methods`,
359
414
  });
360
415
  }
416
+ if (config.mcp) {
417
+ validateActionMCPConfig(scope, name, config);
418
+ }
419
+ };
420
+
421
+ const zodObjectShape = (schema: ZodType): Record<string, unknown> | undefined => {
422
+ const def = (schema as {def?: {type?: string; shape?: Record<string, unknown>}}).def;
423
+ return def?.type === "object" ? def.shape : undefined;
424
+ };
425
+
426
+ /** The MCP tool's arguments are one object, so the action's input schema must be an object. */
427
+ const validateActionMCPConfig = (
428
+ scope: ActionScope,
429
+ name: string,
430
+ config: BaseActionConfig<unknown, unknown, unknown>
431
+ ): void => {
432
+ const mcpName = config.mcp?.name;
433
+ if (!mcpName || !MCP_TOOL_NAME_PATTERN.test(mcpName)) {
434
+ throw new APIError({
435
+ status: 500,
436
+ title: `Action "${name}" (${scope}) has an invalid mcp.name "${mcpName ?? ""}". MCP tool names must match ${MCP_TOOL_NAME_PATTERN.toString()}`,
437
+ });
438
+ }
439
+ const inputField = config.method === "GET" ? "query" : "body";
440
+ const inputSchema = config.method === "GET" ? config.query : config.body;
441
+ if (!inputSchema) {
442
+ return;
443
+ }
444
+ const shape = zodObjectShape(inputSchema);
445
+ if (!shape) {
446
+ throw new APIError({
447
+ status: 500,
448
+ title: `Action "${name}" (${scope}) sets mcp, so its ${inputField} schema must be a z.object()`,
449
+ });
450
+ }
451
+ if (scope === "instance" && "id" in shape) {
452
+ throw new APIError({
453
+ status: 500,
454
+ title: `Action "${name}" (instance) sets mcp, so its ${inputField} schema cannot define "id"; the MCP tool uses id for the document`,
455
+ });
456
+ }
361
457
  };
362
458
 
363
459
  export const assertNoActionCollisions = <T>(
@@ -436,6 +532,22 @@ const buildActionMiddleware = <T>(
436
532
  options.accessControl,
437
533
  options.access
438
534
  );
535
+ // A write action on a user record is a write to that user.
536
+ if (action.method !== "GET") {
537
+ await assertCanWriteTargetUser({
538
+ accessControl: options.accessControl,
539
+ actor: req.user,
540
+ modelName: model.modelName,
541
+ target: doc,
542
+ });
543
+ await assertCanWriteUserIdentity({
544
+ accessControl: options.accessControl,
545
+ actor: req.user,
546
+ body: req.body,
547
+ modelName: model.modelName,
548
+ target: doc,
549
+ });
550
+ }
439
551
  return next();
440
552
  } catch (error) {
441
553
  return next(error);
@@ -480,6 +592,16 @@ const buildActionMiddleware = <T>(
480
592
  return chain;
481
593
  };
482
594
 
595
+ /** True when any instance or collection action opts into MCP with `mcp`. */
596
+ export const hasMCPActions = <T>(
597
+ options: Pick<ModelRouterOptions<T>, "instanceActions" | "collectionActions">
598
+ ): boolean => {
599
+ return [
600
+ ...Object.values(options.instanceActions ?? {}),
601
+ ...Object.values(options.collectionActions ?? {}),
602
+ ].some((config) => Boolean(config.mcp));
603
+ };
604
+
483
605
  export const registerActionRoutes = <T>(
484
606
  router: express.Router,
485
607
  model: Model<T>,
@@ -792,3 +792,81 @@ describe("array operation with undefined preUpdate return", () => {
792
792
  expect(res.body.title).toContain("preUpdate hook error");
793
793
  });
794
794
  });
795
+
796
+ describe("array subdocument PATCH with a stripping preUpdate", () => {
797
+ let app: express.Application;
798
+ let apple: Food;
799
+ let agent: TestAgent;
800
+
801
+ beforeEach(async () => {
802
+ const [admin] = await setupDb();
803
+ apple = await FoodModel.create({
804
+ calories: 100,
805
+ categories: [
806
+ {name: "Fruit", show: true},
807
+ {name: "Popular", show: false},
808
+ ],
809
+ hidden: false,
810
+ name: "Apple",
811
+ ownerId: admin._id,
812
+ });
813
+ });
814
+
815
+ const mountStrippingRouter = async (
816
+ preUpdate: (body: Partial<Food>) => Partial<Food>
817
+ ): Promise<void> => {
818
+ app = getBaseServer();
819
+ setupAuth(app, UserModel as unknown as AuthUserModel);
820
+ addAuthRoutes(app, UserModel as unknown as AuthUserModel);
821
+ app.use(
822
+ "/food",
823
+ modelRouter(FoodModel, {
824
+ allowAnonymous: true,
825
+ permissions: {
826
+ create: [Permissions.IsAdmin],
827
+ delete: [Permissions.IsAdmin],
828
+ list: [Permissions.IsAdmin],
829
+ read: [Permissions.IsAdmin],
830
+ update: [Permissions.IsAdmin],
831
+ },
832
+ preUpdate: (body) => preUpdate(body as Partial<Food>),
833
+ })
834
+ );
835
+ agent = await authAsUser(app, "admin");
836
+ };
837
+
838
+ it("keeps a subdocument unchanged when preUpdate strips the array field", async () => {
839
+ await mountStrippingRouter((body) => {
840
+ const {categories: _categories, ...rest} = body;
841
+ return rest;
842
+ });
843
+ const categoryId = apple.categories[0]._id;
844
+ await agent
845
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
846
+ .send({categories: {name: "ViaArraySubroute", show: false}})
847
+ .expect(200);
848
+ const stored = await FoodModel.findById(apple._id).lean();
849
+ expect(stored?.categories?.[0]?.name).toBe("Fruit");
850
+ expect(stored?.categories?.[0]?.show).toBe(true);
851
+ });
852
+
853
+ it("applies only the subdocument fields that survive preUpdate", async () => {
854
+ await mountStrippingRouter((body) => ({
855
+ categories: (body.categories ?? []).map((category) => ({
856
+ ...((category as {toObject?: () => FoodCategory}).toObject?.() ?? category),
857
+ show: true,
858
+ })) as Food["categories"],
859
+ }));
860
+ const categoryId = apple.categories[1]._id;
861
+ const res = await agent
862
+ .patch(`/food/${apple._id}/categories/${categoryId}`)
863
+ .send({categories: {name: "Renamed", show: false}})
864
+ .expect(200);
865
+ expect(res.body.data.categories[1].name).toBe("Renamed");
866
+ expect(res.body.data.categories[1]._id).toBe(String(categoryId));
867
+ const stored = await FoodModel.findById(apple._id).lean();
868
+ expect(stored?.categories?.[1]?.name).toBe("Renamed");
869
+ expect(stored?.categories?.[1]?.show).toBe(true);
870
+ expect(String(stored?.categories?.[1]?._id)).toBe(String(categoryId));
871
+ });
872
+ });
package/src/api.test.ts CHANGED
@@ -453,6 +453,42 @@ describe("@terreno/api", () => {
453
453
  expect(res.body.data[1].name).toBe("Apple");
454
454
  });
455
455
 
456
+ it("list rejects sort fields outside queryFields, options.sort, and sortFields", async () => {
457
+ await FoodModel.create({calories: 200, hidden: true, name: "Apple", ownerId: admin._id});
458
+ const listOptions = {
459
+ allowAnonymous: true,
460
+ permissions: {
461
+ create: [Permissions.IsAny],
462
+ delete: [Permissions.IsAny],
463
+ list: [Permissions.IsAny],
464
+ read: [Permissions.IsAny],
465
+ update: [Permissions.IsAny],
466
+ },
467
+ queryFields: ["name"],
468
+ sort: "-created" as const,
469
+ };
470
+ app.use("/food", modelRouter(FoodModel, listOptions));
471
+ app.use("/foodSortable", modelRouter(FoodModel, {...listOptions, sortFields: ["calories"]}));
472
+ server = supertest(app);
473
+
474
+ let res = await server.get("/food?sort=hidden%20name").expect(400);
475
+ expect(res.body.code).toBe("sort-field-not-allowed");
476
+ expect(res.body.meta.sortField).toBe("hidden");
477
+ await server.get("/food?sort=-calories").expect(400);
478
+ await server.get("/food?sort[calories]=1").expect(400);
479
+ await server.get("/food?sort=name&sort=calories").expect(400);
480
+
481
+ // queryFields and the router's default sort fields stay sortable.
482
+ await server.get("/food?sort=-name").expect(200);
483
+ await server.get("/food?sort=created%20-name").expect(200);
484
+ await server.get("/food?sort=%2Bname").expect(200);
485
+
486
+ // An explicit sortFields list adds fields that are not filterable.
487
+ res = await server.get("/foodSortable?sort=-calories").expect(200);
488
+ expect(res.body.data[0].name).toBe("Apple");
489
+ await server.get("/foodSortable?sort=hidden").expect(400);
490
+ });
491
+
456
492
  it("queryFilter error is handled", async () => {
457
493
  app.use(
458
494
  "/food",
package/src/api.ts CHANGED
@@ -12,6 +12,7 @@ import mongoose, {type Document, type Model} from "mongoose";
12
12
  import {
13
13
  assertNoActionCollisions,
14
14
  type CollectionActionConfig,
15
+ hasMCPActions,
15
16
  type InstanceActionConfig,
16
17
  registerActionRoutes,
17
18
  } from "./actions";
@@ -35,7 +36,7 @@ import {
35
36
  passthroughOrWrapWrite,
36
37
  } from "./errors";
37
38
  import {logger} from "./logger";
38
- import {registerMCPModel, updateMCPRegistryOptions} from "./mcp/registry";
39
+ import {registerMCPActionModel, registerMCPModel, updateMCPRegistryOptions} from "./mcp/registry";
39
40
  import type {MCPConfig} from "./mcp/types";
40
41
  import {
41
42
  createOpenApiMiddleware,
@@ -54,8 +55,10 @@ import {checkPermissions, permissionMiddleware, type RESTPermissions} from "./pe
54
55
  import type {PopulatePath} from "./populate";
55
56
  import {resolveModelRouterAccess, validateAccessWriteBody} from "./rbac/modelRouterAccess";
56
57
  import type {AnyTerrenoAccess, ModelRouterAccessOptions} from "./rbac/types";
58
+ import {assertCanWriteTargetUser, assertCanWriteUserIdentity} from "./rbac/userWriteGuards";
57
59
  import {warnRealtimeDeprecated} from "./realtime/deprecation";
58
60
  import type {RealtimeConfig} from "./realtime/types";
61
+ import {checkSortFields, getAllowedSortFields} from "./sortFields";
59
62
  import {
60
63
  type ExecutorConcurrencyCheck,
61
64
  executeCreate,
@@ -211,6 +214,13 @@ export interface ModelRouterOptions<T> {
211
214
  * Note: you should have an index field on these fields or Mongo may slow down considerably.
212
215
  * */
213
216
  sort?: string | {[key: string]: "ascending" | "descending"};
217
+ /**
218
+ * Extra fields that list requests may sort by. A client `sort` may name only fields in
219
+ * `queryFields`, fields named in `sort`, and fields listed here; any other field returns
220
+ * 400 `sort-field-not-allowed`. Do not list fields that some readers cannot see (RBAC
221
+ * field views, responseHandler stripping): sort order reveals their values.
222
+ */
223
+ sortFields?: string[];
214
224
  /**
215
225
  * Default queries to provide to Mongo before any user queries or transforms happen when making
216
226
  * list queries. Accepts any Mongoose-style queries, and runs for all user types.
@@ -532,6 +542,39 @@ const checkQueryParamAllowed = (
532
542
  }
533
543
  };
534
544
 
545
+ // Sorting by a field discloses its order even when responses hide it, so list sorts are
546
+ // limited to fields the router declares sortable (queryFields, options.sort, sortFields).
547
+ const checkListSortAllowed = <T>(
548
+ sort: unknown,
549
+ options: ModelRouterOptions<T>,
550
+ modelName: string
551
+ ): void => {
552
+ const allowed = getAllowedSortFields(options);
553
+ const result = checkSortFields(sort, allowed);
554
+ if (result.allowed) {
555
+ return;
556
+ }
557
+ if (result.error === "invalid-sort") {
558
+ throw new BadRequestError({
559
+ code: "invalid-sort",
560
+ detail: "sort must be a space-separated list of fields, each optionally prefixed with -.",
561
+ source: {parameter: "sort"},
562
+ title: "Invalid sort",
563
+ });
564
+ }
565
+ const allowedList = allowed.length > 0 ? allowed.join(", ") : "(none)";
566
+ throw new BadRequestError({
567
+ code: "sort-field-not-allowed",
568
+ detail:
569
+ `${result.field} is not allowed as a sort field. ` +
570
+ `Add "${result.field}" to sortFields or queryFields on the ${modelName} modelRouter ` +
571
+ `to sort on it. Allowed: ${allowedList}.`,
572
+ meta: {allowedSortFields: allowed, model: modelName, sortField: result.field},
573
+ source: {parameter: "sort"},
574
+ title: "Sort field not allowed",
575
+ });
576
+ };
577
+
535
578
  // Handles dot notation patches, creates a normal object to be used for updates.
536
579
  // function flattenDotNotationPatch(data: any) {
537
580
  // const result = {};
@@ -696,6 +739,8 @@ export function modelRouter<T>(
696
739
  // owns the catalog entry and MCP shares that routePath key.
697
740
  if (options.mcp && path === undefined) {
698
741
  registerMCPModel(model, options.mcp, options);
742
+ } else if (path === undefined && hasMCPActions(options)) {
743
+ registerMCPActionModel(model, options);
699
744
  }
700
745
 
701
746
  const shouldDeferBuild = path !== undefined && Boolean(options.access) && !options.accessControl;
@@ -775,7 +820,8 @@ const _buildModelRouter = <T>(
775
820
  if (routePath) {
776
821
  replaceCollectionOptions(routePath, options as unknown as ModelRouterOptions<unknown>);
777
822
  }
778
- if (options.mcp) {
823
+ // A routed router's catalog entry was replaced by routePath above; only pathless ones need this.
824
+ if (options.mcp || (!routePath && hasMCPActions(options))) {
779
825
  updateMCPRegistryOptions(model.modelName, options as unknown as ModelRouterOptions<unknown>);
780
826
  }
781
827
 
@@ -840,6 +886,9 @@ const _buildModelRouter = <T>(
840
886
  // Runs before query validation so a field missing from queryFields is always
841
887
  // reported with this error, whatever the validator's settings.
842
888
  (req: Request, _res: Response, next: NextFunction): void => {
889
+ if (req.query.sort !== undefined) {
890
+ checkListSortAllowed(req.query.sort, options, model.modelName);
891
+ }
843
892
  for (const queryParam of Object.keys(req.query)) {
844
893
  if (PAGINATION_QUERY_PARAMS.includes(queryParam)) {
845
894
  continue;
@@ -1270,6 +1319,13 @@ const _buildModelRouter = <T>(
1270
1319
  });
1271
1320
  }
1272
1321
 
1322
+ await assertCanWriteTargetUser({
1323
+ accessControl: options.accessControl,
1324
+ actor: req.user,
1325
+ modelName: model.modelName,
1326
+ target: doc,
1327
+ });
1328
+
1273
1329
  const field = req.params.field as string;
1274
1330
  const itemId = req.params.itemId as string;
1275
1331
 
@@ -1317,9 +1373,17 @@ const _buildModelRouter = <T>(
1317
1373
  });
1318
1374
  }
1319
1375
  // For PATCHing an item by ID, we need to merge the objects so we don't override the _id or
1320
- // other parts of the subdocument.
1376
+ // other parts of the subdocument. Merge into a detached copy: the array elements are the
1377
+ // loaded document's live subdocuments, and only the body that survives the hooks below
1378
+ // may change the document.
1321
1379
  if (operation === "PATCH" && isValidObjectId(itemId)) {
1322
- Object.assign(array[index] as object, req.body[field]);
1380
+ const current = array[index] as {$clone?: () => object} | object;
1381
+ const detached =
1382
+ typeof (current as {$clone?: unknown}).$clone === "function"
1383
+ ? (current as {$clone: () => object}).$clone()
1384
+ : {...current};
1385
+ Object.assign(detached, req.body[field]);
1386
+ array[index] = detached;
1323
1387
  } else if (operation === "PATCH") {
1324
1388
  // For PATCHing a string array, we can replace the whole object.
1325
1389
  array[index] = req.body[field];
@@ -1336,6 +1400,14 @@ const _buildModelRouter = <T>(
1336
1400
  }
1337
1401
  let body = await applyArrayOperationUpdateHooks({[field]: array} as unknown as Partial<T>, req);
1338
1402
 
1403
+ await assertCanWriteUserIdentity({
1404
+ accessControl: options.accessControl,
1405
+ actor: req.user,
1406
+ body,
1407
+ modelName: model.modelName,
1408
+ target: doc,
1409
+ });
1410
+
1339
1411
  body = omitUserRolesFromWriteBody(
1340
1412
  model.modelName,
1341
1413
  options.accessControl,