@terreno/api 57.16.1 → 57.17.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/dist/mcp/auth.js CHANGED
@@ -3,10 +3,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.extractUserFromHeaders = void 0;
6
+ exports.extractUserFromHeaders = exports.extractAuthFromHeaders = exports.bearerFromHeaders = exports.isCredentialEpochStale = exports.userTokenEpoch = void 0;
7
7
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
8
8
  const luxon_1 = require("luxon");
9
9
  const logger_1 = require("../logger");
10
+ const mcpOAuthToken_1 = require("../models/mcpOAuthToken");
10
11
  const mcpServiceToken_1 = require("../models/mcpServiceToken");
11
12
  const plugins_1 = require("../plugins");
12
13
  /**
@@ -24,35 +25,82 @@ const rejectIfDisabled = (user, source) => {
24
25
  }
25
26
  return user;
26
27
  };
28
+ /** The user's credential generation; a password reset or session revocation increments it. */
29
+ const userTokenEpoch = (user) => {
30
+ const tokenEpoch = user?.tokenEpoch;
31
+ return typeof tokenEpoch === "number" ? tokenEpoch : 0;
32
+ };
33
+ exports.userTokenEpoch = userTokenEpoch;
27
34
  /**
28
- * Extract user from raw headers using whichever auth provider is configured.
29
- * Works with both JWT and Better Auth, mirroring authenticateMiddleware behavior.
35
+ * True when a credential minted under `issuedEpoch` predates the user's current tokenEpoch.
36
+ * A credential stored before the field existed counts as epoch 0, as a refresh token without
37
+ * `te` does.
30
38
  */
31
- const extractUserFromHeaders = async (headers, context) => {
32
- const { userModel, betterAuth, mcpServiceTokens } = context;
39
+ const isCredentialEpochStale = (issuedEpoch, user) => (issuedEpoch ?? 0) !== (0, exports.userTokenEpoch)(user);
40
+ exports.isCredentialEpochStale = isCredentialEpochStale;
41
+ const bearerFromHeaders = (headers) => {
33
42
  const authorization = typeof headers.authorization === "string"
34
43
  ? headers.authorization
35
44
  : Array.isArray(headers.authorization)
36
45
  ? headers.authorization[0]
37
46
  : undefined;
38
47
  const token = authorization?.startsWith("Bearer ") ? authorization.slice(7) : authorization;
39
- // Resolve MCP service tokens before session/JWT auth because mcp_ is a distinct credential type.
40
- if (mcpServiceTokens && token?.startsWith("mcp_")) {
41
- const serviceToken = await mcpServiceToken_1.McpServiceToken.verify(token);
42
- if (!serviceToken) {
43
- return undefined;
44
- }
45
- const user = await userModel.findById(serviceToken.userId);
46
- const activeUser = rejectIfDisabled(user, "MCP service token");
47
- if (!activeUser) {
48
- return undefined;
49
- }
50
- void mcpServiceToken_1.McpServiceToken.updateOne({ _id: serviceToken._id }, { $set: { lastUsedAt: luxon_1.DateTime.now().toJSDate() } }).catch((error) => {
51
- logger_1.logger.debug(`MCP service token last-used update failed: ${error}`);
52
- });
53
- return activeUser;
48
+ return { authorization, token };
49
+ };
50
+ exports.bearerFromHeaders = bearerFromHeaders;
51
+ const authenticateServiceToken = async (token, userModel) => {
52
+ const serviceToken = await mcpServiceToken_1.McpServiceToken.verify(token);
53
+ if (!serviceToken) {
54
+ return undefined;
55
+ }
56
+ const user = await userModel.findById(serviceToken.userId);
57
+ const activeUser = rejectIfDisabled(user, "MCP service token");
58
+ if (!activeUser) {
59
+ return undefined;
60
+ }
61
+ if ((0, exports.isCredentialEpochStale)(serviceToken.tokenEpoch, activeUser)) {
62
+ logger_1.logger.warn(`[mcp] Revoking an MCP service token issued before user ${activeUser.id}'s credentials changed`);
63
+ await mcpServiceToken_1.McpServiceToken.updateOne({ _id: serviceToken._id, revokedAt: { $exists: false } }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
64
+ return undefined;
65
+ }
66
+ void mcpServiceToken_1.McpServiceToken.updateOne({ _id: serviceToken._id }, { $set: { lastUsedAt: luxon_1.DateTime.now().toJSDate() } }).catch((error) => {
67
+ logger_1.logger.debug(`MCP service token last-used update failed: ${error}`);
68
+ });
69
+ return { credential: "mcp-service-token", user: activeUser };
70
+ };
71
+ const authenticateOAuthAccessToken = async (token, userModel) => {
72
+ const accessToken = await mcpOAuthToken_1.McpOAuthToken.verifyAccessToken(token);
73
+ if (!accessToken) {
74
+ return undefined;
75
+ }
76
+ const user = await userModel.findById(accessToken.userId);
77
+ const activeUser = rejectIfDisabled(user, "MCP OAuth");
78
+ if (!activeUser) {
79
+ return undefined;
80
+ }
81
+ if ((0, exports.isCredentialEpochStale)(accessToken.tokenEpoch, activeUser)) {
82
+ logger_1.logger.warn(`[mcp] Revoking an MCP OAuth grant issued before user ${activeUser.id}'s credentials changed`);
83
+ await mcpOAuthToken_1.McpOAuthToken.revokeFamily(accessToken.familyId);
84
+ return undefined;
85
+ }
86
+ const scopes = (accessToken.scope ?? "").split(" ").filter((scope) => scope.length > 0);
87
+ return { credential: "oauth", scopes, user: activeUser };
88
+ };
89
+ /**
90
+ * Resolve the caller and the credential type from raw headers using whichever auth providers
91
+ * are configured, mirroring authenticateMiddleware behavior: `mcp_` service tokens and `mcpat_`
92
+ * OAuth access tokens first (each is a distinct credential type), then a Better Auth session,
93
+ * then a Terreno JWT.
94
+ */
95
+ const extractAuthFromHeaders = async (headers, context) => {
96
+ const { userModel, betterAuth, mcpServiceTokens, mcpOAuth } = context;
97
+ const { authorization, token } = (0, exports.bearerFromHeaders)(headers);
98
+ if (mcpServiceTokens && token?.startsWith(mcpServiceToken_1.MCP_SERVICE_TOKEN_PREFIX)) {
99
+ return authenticateServiceToken(token, userModel);
100
+ }
101
+ if (mcpOAuth && token?.startsWith(mcpOAuthToken_1.MCP_OAUTH_ACCESS_TOKEN_PREFIX)) {
102
+ return authenticateOAuthAccessToken(token, userModel);
54
103
  }
55
- // Try Better Auth first if configured.
56
104
  if (betterAuth) {
57
105
  try {
58
106
  const session = await betterAuth.api.getSession({
@@ -64,7 +112,8 @@ const extractUserFromHeaders = async (headers, context) => {
64
112
  // working whether or not the consumer's model has the findOneOrNone plugin applied.
65
113
  const appUser = await (0, plugins_1.findOneOrNoneFor)(userModel, { betterAuthId: session.user.id });
66
114
  if (appUser) {
67
- return rejectIfDisabled(appUser, "Better Auth");
115
+ const activeUser = rejectIfDisabled(appUser, "Better Auth");
116
+ return activeUser ? { credential: "better-auth-session", user: activeUser } : undefined;
68
117
  }
69
118
  }
70
119
  }
@@ -72,11 +121,7 @@ const extractUserFromHeaders = async (headers, context) => {
72
121
  logger_1.logger.debug(`MCP Better Auth session extraction failed: ${error}`);
73
122
  }
74
123
  }
75
- // Try JWT auth
76
- if (!authorization) {
77
- return undefined;
78
- }
79
- if (!token) {
124
+ if (!authorization || !token) {
80
125
  return undefined;
81
126
  }
82
127
  const tokenSecret = process.env.TOKEN_SECRET;
@@ -93,11 +138,21 @@ const extractUserFromHeaders = async (headers, context) => {
93
138
  return undefined;
94
139
  }
95
140
  const user = await userModel.findById(userId);
96
- return rejectIfDisabled(user, "JWT");
141
+ const activeUser = rejectIfDisabled(user, "JWT");
142
+ return activeUser ? { credential: "jwt", user: activeUser } : undefined;
97
143
  }
98
144
  catch (error) {
99
145
  logger_1.logger.debug(`MCP JWT verification failed: ${error}`);
100
146
  return undefined;
101
147
  }
102
148
  };
149
+ exports.extractAuthFromHeaders = extractAuthFromHeaders;
150
+ /**
151
+ * Extract user from raw headers using whichever auth provider is configured.
152
+ * Works with both JWT and Better Auth, mirroring authenticateMiddleware behavior.
153
+ * Use {@link extractAuthFromHeaders} when the credential type matters.
154
+ */
155
+ const extractUserFromHeaders = async (headers, context) => {
156
+ return (await (0, exports.extractAuthFromHeaders)(headers, context))?.user;
157
+ };
103
158
  exports.extractUserFromHeaders = extractUserFromHeaders;
@@ -10,7 +10,11 @@ import type { MCPToolArgs } from "./types";
10
10
  * or `req.headers` get the shape they expect instead of a TypeError. `isMCPRequest` lets
11
11
  * a hook detect the MCP path when it needs to behave differently from HTTP.
12
12
  */
13
- export declare const createMCPRequest: ({ body, user, }: {
13
+ export declare const createMCPRequest: ({ body, params, query, user, }: {
14
14
  body?: MCPToolArgs;
15
+ /** Route params an action tool fills in, such as the instance action's `id`. */
16
+ params?: Record<string, string>;
17
+ /** Tool arguments of a GET action, which REST would read from the query string. */
18
+ query?: Record<string, unknown>;
15
19
  user?: User;
16
20
  }) => express.Request;
@@ -10,14 +10,14 @@ exports.createMCPRequest = void 0;
10
10
  * or `req.headers` get the shape they expect instead of a TypeError. `isMCPRequest` lets
11
11
  * a hook detect the MCP path when it needs to behave differently from HTTP.
12
12
  */
13
- const createMCPRequest = ({ body = {}, user, }) => {
13
+ const createMCPRequest = ({ body = {}, params = {}, query = {}, user, }) => {
14
14
  const request = {
15
15
  body,
16
16
  headers: {},
17
17
  isMCPRequest: true,
18
18
  method: "MCP",
19
- params: {},
20
- query: {},
19
+ params,
20
+ query,
21
21
  user,
22
22
  };
23
23
  return request;
@@ -6,3 +6,6 @@ export declare const handleRead: (entry: MCPRegistryEntry, args: MCPToolArgs, us
6
6
  export declare const handleCreate: (entry: MCPRegistryEntry, args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
7
7
  export declare const handleUpdate: (entry: MCPRegistryEntry, args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
8
8
  export declare const handleDelete: (entry: MCPRegistryEntry, args: MCPToolArgs, user?: User) => Promise<MCPToolResult>;
9
+ export declare const errorMessage: (error: unknown) => string;
10
+ export declare const textResult: (text: string) => MCPToolResult;
11
+ export declare const errorResult: (message: string, cause?: unknown) => MCPToolResult;
@@ -3,11 +3,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.handleDelete = exports.handleUpdate = exports.handleCreate = exports.handleRead = exports.handleList = exports.getMCPErrorCause = void 0;
6
+ exports.errorResult = exports.textResult = exports.errorMessage = exports.handleDelete = exports.handleUpdate = exports.handleCreate = exports.handleRead = exports.handleList = exports.getMCPErrorCause = void 0;
7
7
  const mongoose_1 = __importDefault(require("mongoose"));
8
8
  const api_1 = require("../api");
9
9
  const errors_1 = require("../errors");
10
10
  const permissions_1 = require("../permissions");
11
+ const sortFields_1 = require("../sortFields");
11
12
  const executors_1 = require("../sync/executors");
12
13
  const transformers_1 = require("../transformers");
13
14
  const createMCPRequest_1 = require("./createMCPRequest");
@@ -175,7 +176,7 @@ const execFindByIdQuery = async (query) => {
175
176
  }
176
177
  };
177
178
  const missingDocumentResult = (id) => {
178
- return errorResult(`Document ${id} not found`);
179
+ return (0, exports.errorResult)(`Document ${id} not found`);
179
180
  };
180
181
  /**
181
182
  * Mirror REST's `authenticateMiddleware(options.allowAnonymous)`, which answers 401 before
@@ -189,9 +190,9 @@ const requiresAuthentication = (entry, user) => {
189
190
  /** Map executor/APIError failures onto the MCP error envelope. */
190
191
  const fromExecutorError = (error) => {
191
192
  if ((0, errors_1.isAPIError)(error)) {
192
- return errorResult(error.title, error);
193
+ return (0, exports.errorResult)(error.title, error);
193
194
  }
194
- return errorResult(errorMessage(error), error);
195
+ return (0, exports.errorResult)((0, exports.errorMessage)(error), error);
195
196
  };
196
197
  const deniedWriteFields = (entry, phase) => {
197
198
  return (0, schemaGenerator_1.writeExcludeFields)(entry.config, (0, schemaGenerator_1.restWriteExcludeFields)(phase, entry.options.validation));
@@ -210,25 +211,25 @@ const serializeResponse = async (data, method, entry, user) => {
210
211
  }
211
212
  catch (error) {
212
213
  if ((0, errors_1.isAPIError)(error)) {
213
- return { error: errorResult(error.title, error) };
214
+ return { error: (0, exports.errorResult)(error.title, error) };
214
215
  }
215
- return { error: errorResult(`Response handler failed: ${errorMessage(error)}`, error) };
216
+ return { error: (0, exports.errorResult)(`Response handler failed: ${(0, exports.errorMessage)(error)}`, error) };
216
217
  }
217
218
  };
218
219
  const handleList = async (entry, args, user) => {
219
220
  const { model, config, options } = entry;
220
221
  const maxLimit = config.maxLimit ?? 50;
221
222
  if (requiresAuthentication(entry, user)) {
222
- return errorResult("Permission denied: authentication required");
223
+ return (0, exports.errorResult)("Permission denied: authentication required");
223
224
  }
224
225
  // Check permissions
225
226
  if (!(await (0, permissions_1.checkPermissions)("list", options.permissions.list, user))) {
226
- return errorResult("Permission denied: cannot list");
227
+ return (0, exports.errorResult)("Permission denied: cannot list");
227
228
  }
228
229
  // Build query from args — only fields in queryFields, with an allowlist of operators
229
230
  const { error: queryError, query: builtFilter } = (0, query_1.buildListQuery)({ args, config, options });
230
231
  if (queryError || !builtFilter) {
231
- return errorResult(queryError ?? "Could not build query");
232
+ return (0, exports.errorResult)(queryError ?? "Could not build query");
232
233
  }
233
234
  let query = builtFilter;
234
235
  // Apply query filter
@@ -236,15 +237,15 @@ const handleList = async (entry, args, user) => {
236
237
  try {
237
238
  const filtered = await options.queryFilter(user, query);
238
239
  if (filtered === null) {
239
- return textResult(JSON.stringify({ data: [], more: false, page: 1, total: 0 }));
240
+ return (0, exports.textResult)(JSON.stringify({ data: [], more: false, page: 1, total: 0 }));
240
241
  }
241
242
  query = { ...query, ...filtered };
242
243
  }
243
244
  catch (error) {
244
245
  if ((0, errors_1.isAPIError)(error)) {
245
- return errorResult(error.title, error);
246
+ return (0, exports.errorResult)(error.title, error);
246
247
  }
247
- return errorResult(`queryFilter failed: ${errorMessage(error)}`, error);
248
+ return (0, exports.errorResult)(`queryFilter failed: ${(0, exports.errorMessage)(error)}`, error);
248
249
  }
249
250
  }
250
251
  // Pagination
@@ -255,15 +256,27 @@ const handleList = async (entry, args, user) => {
255
256
  if (page > 1) {
256
257
  builtQuery = builtQuery.skip((page - 1) * limit);
257
258
  }
258
- // Sort
259
- const sort = asOptionalString(args.sort) ?? options.sort;
259
+ // Sort: client keys are limited to declared sortable fields minus excludeFields, because
260
+ // the order of results reveals the order of the sorted field's hidden values.
261
+ const sortArg = asOptionalString(args.sort);
262
+ if (sortArg) {
263
+ const excludeFields = config.excludeFields ?? [];
264
+ const allowedSortFields = (0, sortFields_1.getAllowedSortFields)(options).filter((field) => !(0, schemaGenerator_1.isFieldExcluded)(field, excludeFields));
265
+ const sortCheck = (0, sortFields_1.checkSortFields)(sortArg, allowedSortFields);
266
+ if (!sortCheck.allowed) {
267
+ const allowed = allowedSortFields.length > 0 ? allowedSortFields.join(", ") : "(none)";
268
+ const field = sortCheck.error === "sort-field-not-allowed" ? sortCheck.field : sortArg;
269
+ return (0, exports.errorResult)(`${field} is not an allowed sort field. Allowed: ${allowed}`);
270
+ }
271
+ }
272
+ const sort = sortArg ?? options.sort;
260
273
  if (sort) {
261
274
  builtQuery = builtQuery.sort(sort);
262
275
  }
263
276
  // Populate
264
277
  const { error: populateError, paths: populatePaths } = resolvePopulatePaths(asOptionalString(args.populate), options.populatePaths);
265
278
  if (populateError || !populatePaths) {
266
- return errorResult(populateError ?? "Could not resolve populate paths");
279
+ return (0, exports.errorResult)(populateError ?? "Could not resolve populate paths");
267
280
  }
268
281
  const populatedQuery = (0, api_1.addPopulateToQuery)(builtQuery, populatePaths);
269
282
  const data = await populatedQuery.exec();
@@ -273,21 +286,21 @@ const handleList = async (entry, args, user) => {
273
286
  if ("error" in serialized) {
274
287
  return serialized.error;
275
288
  }
276
- return textResult(JSON.stringify({ data: serialized.value, more, page, total }));
289
+ return (0, exports.textResult)(JSON.stringify({ data: serialized.value, more, page, total }));
277
290
  };
278
291
  exports.handleList = handleList;
279
292
  const handleRead = async (entry, args, user) => {
280
293
  const { model, options } = entry;
281
294
  if (requiresAuthentication(entry, user)) {
282
- return errorResult("Permission denied: authentication required");
295
+ return (0, exports.errorResult)("Permission denied: authentication required");
283
296
  }
284
297
  // Check method-level permission
285
298
  if (!(await (0, permissions_1.checkPermissions)("read", options.permissions.read, user))) {
286
- return errorResult("Permission denied: cannot read");
299
+ return (0, exports.errorResult)("Permission denied: cannot read");
287
300
  }
288
301
  const { error: populateError, paths: populatePaths } = resolvePopulatePaths(asOptionalString(args.populate), options.populatePaths);
289
302
  if (populateError || !populatePaths) {
290
- return errorResult(populateError ?? "Could not resolve populate paths");
303
+ return (0, exports.errorResult)(populateError ?? "Could not resolve populate paths");
291
304
  }
292
305
  const id = asOptionalString(args.id);
293
306
  if (!id) {
@@ -299,19 +312,19 @@ const handleRead = async (entry, args, user) => {
299
312
  }
300
313
  // Check object-level permission
301
314
  if (!(await (0, permissions_1.checkPermissions)("read", options.permissions.read, user, data))) {
302
- return errorResult("Permission denied: cannot read this document");
315
+ return (0, exports.errorResult)("Permission denied: cannot read this document");
303
316
  }
304
317
  const serialized = await serializeResponse(data, "read", entry, user);
305
318
  if ("error" in serialized) {
306
319
  return serialized.error;
307
320
  }
308
- return textResult(JSON.stringify({ data: serialized.value }));
321
+ return (0, exports.textResult)(JSON.stringify({ data: serialized.value }));
309
322
  };
310
323
  exports.handleRead = handleRead;
311
324
  const handleCreate = async (entry, args, user) => {
312
325
  const { model, options } = entry;
313
326
  if (requiresAuthentication(entry, user)) {
314
- return errorResult("Permission denied: authentication required");
327
+ return (0, exports.errorResult)("Permission denied: authentication required");
315
328
  }
316
329
  const body = omitDeniedWriteFields(args, deniedWriteFields(entry, "create"));
317
330
  const req = (0, createMCPRequest_1.createMCPRequest)({ body, user });
@@ -334,14 +347,14 @@ const handleCreate = async (entry, args, user) => {
334
347
  if ("error" in serialized) {
335
348
  return serialized.error;
336
349
  }
337
- return textResult(JSON.stringify({ data: serialized.value }));
350
+ return (0, exports.textResult)(JSON.stringify({ data: serialized.value }));
338
351
  };
339
352
  exports.handleCreate = handleCreate;
340
353
  const handleUpdate = async (entry, args, user) => {
341
354
  const { model, options } = entry;
342
355
  const { id, ...updateFields } = args;
343
356
  if (requiresAuthentication(entry, user)) {
344
- return errorResult("Permission denied: authentication required");
357
+ return (0, exports.errorResult)("Permission denied: authentication required");
345
358
  }
346
359
  const documentId = asOptionalString(id);
347
360
  if (!documentId) {
@@ -369,14 +382,14 @@ const handleUpdate = async (entry, args, user) => {
369
382
  if ("error" in serialized) {
370
383
  return serialized.error;
371
384
  }
372
- return textResult(JSON.stringify({ data: serialized.value }));
385
+ return (0, exports.textResult)(JSON.stringify({ data: serialized.value }));
373
386
  };
374
387
  exports.handleUpdate = handleUpdate;
375
388
  const handleDelete = async (entry, args, user) => {
376
389
  const { model, options } = entry;
377
390
  const { id } = args;
378
391
  if (requiresAuthentication(entry, user)) {
379
- return errorResult("Permission denied: authentication required");
392
+ return (0, exports.errorResult)("Permission denied: authentication required");
380
393
  }
381
394
  const documentId = asOptionalString(id);
382
395
  if (!documentId) {
@@ -394,15 +407,17 @@ const handleDelete = async (entry, args, user) => {
394
407
  catch (error) {
395
408
  return fromExecutorError(error);
396
409
  }
397
- return textResult(JSON.stringify({ success: true }));
410
+ return (0, exports.textResult)(JSON.stringify({ success: true }));
398
411
  };
399
412
  exports.handleDelete = handleDelete;
400
413
  const errorMessage = (error) => {
401
414
  return error instanceof Error ? error.message : String(error);
402
415
  };
416
+ exports.errorMessage = errorMessage;
403
417
  const textResult = (text) => ({
404
418
  content: [{ text, type: "text" }],
405
419
  });
420
+ exports.textResult = textResult;
406
421
  const errorResult = (message, cause) => {
407
422
  const result = {
408
423
  content: [{ text: JSON.stringify({ error: message }), type: "text" }],
@@ -413,3 +428,4 @@ const errorResult = (message, cause) => {
413
428
  }
414
429
  return result;
415
430
  };
431
+ exports.errorResult = errorResult;
@@ -0,0 +1,14 @@
1
+ import type { Application } from "express";
2
+ import { type OpenApiMiddleware } from "../api";
3
+ import { type UserModel } from "../auth";
4
+ import { type ResolvedMcpOAuthOptions } from "./oauthMetadata";
5
+ export interface McpOAuthRoutesOptions {
6
+ oauth: ResolvedMcpOAuthOptions;
7
+ openApi?: OpenApiMiddleware;
8
+ userModel: UserModel;
9
+ }
10
+ /**
11
+ * Mount the MCP OAuth authorization server: discovery documents, client registration (only with
12
+ * `dynamicClientRegistration`), authorize + consent decision, token, and revocation endpoints.
13
+ */
14
+ export declare const addMcpOAuthRoutes: (app: Application, options: McpOAuthRoutesOptions) => void;