@terreno/api 57.16.2 → 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
@@ -0,0 +1,618 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.addMcpOAuthRoutes = void 0;
7
+ /**
8
+ * Terreno-native OAuth 2.1 authorization server for `/mcp`, for apps that authenticate with
9
+ * Terreno JWTs. Remote MCP clients (Claude.ai connectors, ChatGPT apps) discover it through
10
+ * RFC 9728 / RFC 8414 metadata, register with RFC 7591 dynamic client registration, and run the
11
+ * authorization-code flow with PKCE S256. Terreno is backend-only, so the app hosts the consent
12
+ * screen at `consentUrl` and calls the approve/deny endpoints with the signed-in user's JWT.
13
+ */
14
+ const node_crypto_1 = require("node:crypto");
15
+ const luxon_1 = require("luxon");
16
+ const mongoose_1 = __importDefault(require("mongoose"));
17
+ const api_1 = require("../api");
18
+ const auth_1 = require("../auth");
19
+ const errors_1 = require("../errors");
20
+ const logger_1 = require("../logger");
21
+ const mcpOAuthAuthorization_1 = require("../models/mcpOAuthAuthorization");
22
+ const mcpOAuthClient_1 = require("../models/mcpOAuthClient");
23
+ const mcpOAuthToken_1 = require("../models/mcpOAuthToken");
24
+ const mcpServiceToken_1 = require("../models/mcpServiceToken");
25
+ const openApiBuilder_1 = require("../openApiBuilder");
26
+ const auth_2 = require("./auth");
27
+ const oauthMetadata_1 = require("./oauthMetadata");
28
+ // Keep a used code's record long enough to detect a replay and revoke what it issued.
29
+ const USED_CODE_RETENTION_SECONDS = 60 * 60;
30
+ const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
31
+ const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9._~-]{43,128}$/;
32
+ const MAX_CLIENT_NAME_LENGTH = 200;
33
+ const MAX_REDIRECT_URIS = 10;
34
+ /** An RFC 6749 §5.2-shaped error, sent as `{error, error_description}` instead of JSON:API. */
35
+ class OAuthProtocolError extends Error {
36
+ error;
37
+ status;
38
+ constructor(error, description, status = 400) {
39
+ super(description);
40
+ this.error = error;
41
+ this.status = status;
42
+ }
43
+ }
44
+ /** Issue a pair into a family; a family revoked by a concurrent request answers `invalid_grant`. */
45
+ const issueOrInvalidGrant = async (options) => {
46
+ try {
47
+ return await mcpOAuthToken_1.McpOAuthToken.issue(options);
48
+ }
49
+ catch (error) {
50
+ if (error instanceof mcpOAuthToken_1.McpOAuthFamilyRevokedError) {
51
+ logger_1.logger.warn("[MCPOAuth] Refused to issue into a revoked token family", {
52
+ clientId: options.clientId,
53
+ });
54
+ throw new OAuthProtocolError("invalid_grant", "The grant was revoked");
55
+ }
56
+ throw error;
57
+ }
58
+ };
59
+ const oauthHandler = (handler) => {
60
+ return async (req, res, next) => {
61
+ try {
62
+ await handler(req, res);
63
+ }
64
+ catch (error) {
65
+ if (error instanceof OAuthProtocolError) {
66
+ res.setHeader("Cache-Control", "no-store");
67
+ (0, oauthMetadata_1.sendProtocolJson)(res, error.status, {
68
+ error: error.error,
69
+ error_description: error.message,
70
+ });
71
+ return;
72
+ }
73
+ next(error);
74
+ }
75
+ };
76
+ };
77
+ const stringParam = (value) => {
78
+ return typeof value === "string" && value.length > 0 ? value : undefined;
79
+ };
80
+ const hostMatches = (hostname, pattern) => {
81
+ if (pattern.startsWith("*.")) {
82
+ const suffix = pattern.slice(1);
83
+ return hostname.endsWith(suffix) && hostname.length > suffix.length;
84
+ }
85
+ return hostname === pattern;
86
+ };
87
+ /** Returns why a redirect URI is not acceptable, or undefined when it is. */
88
+ const redirectUriProblem = (uri, allowedHosts) => {
89
+ if (typeof uri !== "string") {
90
+ return "redirect_uris must be strings";
91
+ }
92
+ let parsed;
93
+ try {
94
+ parsed = new URL(uri);
95
+ }
96
+ catch {
97
+ return `${uri} is not an absolute URL`;
98
+ }
99
+ if (parsed.hash) {
100
+ return `${uri} must not contain a fragment`;
101
+ }
102
+ const hostname = parsed.hostname.toLowerCase();
103
+ const isLoopback = oauthMetadata_1.LOOPBACK_HOSTS.has(hostname);
104
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback)) {
105
+ return `${uri} must use https (http is allowed only for loopback hosts)`;
106
+ }
107
+ if (!allowedHosts.some((pattern) => hostMatches(hostname, pattern))) {
108
+ return `${hostname} is not an allowed redirect host`;
109
+ }
110
+ return undefined;
111
+ };
112
+ const parseScope = (scope, supported) => {
113
+ if (!scope) {
114
+ return supported.join(" ");
115
+ }
116
+ const requested = scope.split(" ").filter(Boolean);
117
+ const unknown = requested.filter((value) => !supported.includes(value));
118
+ if (unknown.length > 0) {
119
+ throw new OAuthProtocolError("invalid_scope", `Unsupported scope: ${unknown.join(" ")}`);
120
+ }
121
+ return requested.join(" ");
122
+ };
123
+ const normalizeResource = (resource) => resource.replace(/\/$/, "");
124
+ const pkceS256 = (verifier) => (0, node_crypto_1.createHash)("sha256").update(verifier).digest("base64url");
125
+ const appendParams = (base, params) => {
126
+ const url = new URL(base);
127
+ for (const [key, value] of Object.entries(params)) {
128
+ if (value !== undefined) {
129
+ url.searchParams.set(key, value);
130
+ }
131
+ }
132
+ return url.toString();
133
+ };
134
+ const userIsDisabled = (user) => {
135
+ return Boolean(user?.disabled);
136
+ };
137
+ const rejectDelegatedCredentials = (req, _res, next) => {
138
+ const { token } = (0, auth_2.bearerFromHeaders)(req.headers);
139
+ if (token?.startsWith(mcpServiceToken_1.MCP_SERVICE_TOKEN_PREFIX) ||
140
+ token?.startsWith(mcpOAuthToken_1.MCP_OAUTH_ACCESS_TOKEN_PREFIX)) {
141
+ next(new errors_1.UnauthorizedError("Delegated MCP credentials cannot decide OAuth requests"));
142
+ return;
143
+ }
144
+ next();
145
+ };
146
+ const consentGuards = [rejectDelegatedCredentials, (0, auth_1.authenticateMiddleware)()];
147
+ const requireUser = (req) => {
148
+ const user = req.user;
149
+ if (!user?._id) {
150
+ throw new errors_1.UnauthorizedError("Unauthorized");
151
+ }
152
+ return user;
153
+ };
154
+ /** Load a pending request for the consent endpoints, or explain why it cannot be decided. */
155
+ const loadPendingAuthorization = async (requestId) => {
156
+ const authorization = await mcpOAuthAuthorization_1.McpOAuthAuthorization.findOneOrNone({ requestId });
157
+ if (!authorization) {
158
+ throw new errors_1.NotFoundError("Authorization request not found");
159
+ }
160
+ if (authorization.status !== "pending") {
161
+ throw new errors_1.ConflictError({
162
+ code: "mcp-oauth-request-decided",
163
+ title: "Authorization request was already decided",
164
+ });
165
+ }
166
+ if (luxon_1.DateTime.fromJSDate(authorization.expiresAt) <= luxon_1.DateTime.now()) {
167
+ throw new errors_1.BadRequestError({
168
+ code: "mcp-oauth-request-expired",
169
+ title: "Authorization request expired",
170
+ });
171
+ }
172
+ return authorization;
173
+ };
174
+ const addDiscoveryRoutes = (app, oauth) => {
175
+ const protectedResource = (_req, res) => {
176
+ (0, oauthMetadata_1.sendProtocolJson)(res, 200, (0, oauthMetadata_1.buildProtectedResourceMetadata)(oauth));
177
+ };
178
+ app.get("/.well-known/oauth-protected-resource", protectedResource);
179
+ const resourcePath = (0, oauthMetadata_1.protectedResourceMetadataPath)(oauth.resource);
180
+ if (resourcePath !== "/.well-known/oauth-protected-resource") {
181
+ app.get(resourcePath, protectedResource);
182
+ }
183
+ app.get("/.well-known/oauth-authorization-server", (_req, res) => {
184
+ (0, oauthMetadata_1.sendProtocolJson)(res, 200, (0, oauthMetadata_1.buildAuthorizationServerMetadata)(oauth));
185
+ });
186
+ };
187
+ const addRegistrationRoute = (app, oauth) => {
188
+ app.post("/oauth/register", oauthHandler(async (req, res) => {
189
+ const body = (req.body ?? {});
190
+ const redirectUris = body.redirect_uris;
191
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0) {
192
+ throw new OAuthProtocolError("invalid_redirect_uri", "redirect_uris is required");
193
+ }
194
+ if (redirectUris.length > MAX_REDIRECT_URIS) {
195
+ throw new OAuthProtocolError("invalid_redirect_uri", `At most ${MAX_REDIRECT_URIS} redirect_uris are allowed`);
196
+ }
197
+ for (const uri of redirectUris) {
198
+ const problem = redirectUriProblem(uri, oauth.allowedRedirectHosts);
199
+ if (problem) {
200
+ throw new OAuthProtocolError("invalid_redirect_uri", problem);
201
+ }
202
+ }
203
+ const authMethod = body.token_endpoint_auth_method ?? "none";
204
+ if (authMethod !== "none") {
205
+ throw new OAuthProtocolError("invalid_client_metadata", "Only public clients are supported: token_endpoint_auth_method must be none");
206
+ }
207
+ const grantTypes = body.grant_types ?? oauthMetadata_1.SUPPORTED_GRANT_TYPES;
208
+ if (!Array.isArray(grantTypes) ||
209
+ !grantTypes.includes("authorization_code") ||
210
+ grantTypes.some((grant) => !oauthMetadata_1.SUPPORTED_GRANT_TYPES.includes(grant))) {
211
+ throw new OAuthProtocolError("invalid_client_metadata", "grant_types must include authorization_code and may add refresh_token");
212
+ }
213
+ const responseTypes = body.response_types ?? oauthMetadata_1.SUPPORTED_RESPONSE_TYPES;
214
+ if (!Array.isArray(responseTypes) ||
215
+ responseTypes.some((type) => !oauthMetadata_1.SUPPORTED_RESPONSE_TYPES.includes(type))) {
216
+ throw new OAuthProtocolError("invalid_client_metadata", "response_types must be [code]");
217
+ }
218
+ const clientName = stringParam(body.client_name)?.slice(0, MAX_CLIENT_NAME_LENGTH);
219
+ let scope;
220
+ try {
221
+ scope = body.scope ? parseScope(stringParam(body.scope), oauth.scopesSupported) : undefined;
222
+ }
223
+ catch (error) {
224
+ throw new OAuthProtocolError("invalid_client_metadata", error.message);
225
+ }
226
+ const client = await mcpOAuthClient_1.McpOAuthClient.create({
227
+ clientId: (0, node_crypto_1.randomUUID)(),
228
+ clientName,
229
+ grantTypes: grantTypes,
230
+ redirectUris: redirectUris,
231
+ responseTypes: responseTypes,
232
+ scope,
233
+ });
234
+ logger_1.logger.info("[MCPOAuth] Registered client", { clientId: client.clientId, clientName });
235
+ res.setHeader("Cache-Control", "no-store");
236
+ (0, oauthMetadata_1.sendProtocolJson)(res, 201, {
237
+ client_id: client.clientId,
238
+ client_id_issued_at: Math.floor(luxon_1.DateTime.fromJSDate(client.created).toSeconds()),
239
+ client_name: client.clientName,
240
+ grant_types: client.grantTypes,
241
+ redirect_uris: client.redirectUris,
242
+ response_types: client.responseTypes,
243
+ scope: client.scope,
244
+ token_endpoint_auth_method: "none",
245
+ });
246
+ }));
247
+ };
248
+ const addAuthorizeRoute = (app, oauth) => {
249
+ app.get("/oauth/authorize", oauthHandler(async (req, res) => {
250
+ const query = req.query;
251
+ const clientId = stringParam(query.client_id);
252
+ if (!clientId) {
253
+ throw new OAuthProtocolError("invalid_request", "client_id is required");
254
+ }
255
+ const client = await mcpOAuthClient_1.McpOAuthClient.findOneOrNone({ clientId });
256
+ if (!client) {
257
+ throw new OAuthProtocolError("invalid_request", "Unknown client_id");
258
+ }
259
+ // RFC 6749 §4.1.2.1: never redirect to an unverified URI, so these two fail in place.
260
+ const requestedRedirect = stringParam(query.redirect_uri);
261
+ const redirectUri = requestedRedirect ??
262
+ (client.redirectUris.length === 1 ? client.redirectUris[0] : undefined);
263
+ if (!redirectUri || !client.redirectUris.includes(redirectUri)) {
264
+ throw new OAuthProtocolError("invalid_request", "redirect_uri does not match a registered redirect URI");
265
+ }
266
+ const state = stringParam(query.state);
267
+ const redirectError = (error, description) => {
268
+ res.redirect(302, appendParams(redirectUri, {
269
+ error,
270
+ error_description: description,
271
+ iss: oauth.issuer,
272
+ state,
273
+ }));
274
+ };
275
+ if (query.response_type !== "code") {
276
+ redirectError("unsupported_response_type", "response_type must be code");
277
+ return;
278
+ }
279
+ const codeChallenge = stringParam(query.code_challenge);
280
+ if (!codeChallenge || !CODE_CHALLENGE_PATTERN.test(codeChallenge)) {
281
+ redirectError("invalid_request", "A PKCE S256 code_challenge is required");
282
+ return;
283
+ }
284
+ if (query.code_challenge_method !== "S256") {
285
+ redirectError("invalid_request", "code_challenge_method must be S256");
286
+ return;
287
+ }
288
+ const resource = stringParam(query.resource);
289
+ if (resource && normalizeResource(resource) !== normalizeResource(oauth.resource)) {
290
+ redirectError("invalid_target", `resource must be ${oauth.resource}`);
291
+ return;
292
+ }
293
+ let scope;
294
+ try {
295
+ scope = parseScope(stringParam(query.scope), oauth.scopesSupported);
296
+ }
297
+ catch (error) {
298
+ redirectError("invalid_scope", error.message);
299
+ return;
300
+ }
301
+ const requestId = (0, mcpOAuthToken_1.generateMcpOAuthSecret)();
302
+ await mcpOAuthAuthorization_1.McpOAuthAuthorization.create({
303
+ clientId,
304
+ codeChallenge,
305
+ expiresAt: luxon_1.DateTime.now().plus({ seconds: oauth.authorizationRequestTtlSeconds }).toJSDate(),
306
+ redirectUri,
307
+ requestId,
308
+ resource: resource ?? oauth.resource,
309
+ scope,
310
+ state,
311
+ status: "pending",
312
+ });
313
+ res.redirect(302, appendParams(oauth.consentUrl, { request: requestId }));
314
+ }));
315
+ };
316
+ const addConsentRoutes = (app, oauth, openApi) => {
317
+ const openApiOptions = { openApi };
318
+ app.get("/oauth/authorize/:request", [
319
+ ...consentGuards,
320
+ (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
321
+ .withTags(["mcp"])
322
+ .withOperationId("getMcpOAuthRequest")
323
+ .withSummary("Read a pending MCP OAuth authorization request")
324
+ .withDescription("Returns what the consent screen shows: the client, where the code goes, and the scope.")
325
+ .withPathParameter("request", { type: "string" })
326
+ .withResponse(200, {
327
+ data: {
328
+ properties: {
329
+ clientId: { type: "string" },
330
+ clientName: { type: "string" },
331
+ expiresAt: { type: "string" },
332
+ redirectHost: { type: "string" },
333
+ redirectUri: { type: "string" },
334
+ requestId: { type: "string" },
335
+ resource: { type: "string" },
336
+ scope: { type: "string" },
337
+ },
338
+ type: "object",
339
+ },
340
+ })
341
+ .build(),
342
+ ], (0, api_1.asyncHandler)(async (req, res) => {
343
+ requireUser(req);
344
+ const authorization = await loadPendingAuthorization(String(req.params.request));
345
+ const client = await mcpOAuthClient_1.McpOAuthClient.findOneOrNone({ clientId: authorization.clientId });
346
+ return res.json({
347
+ data: {
348
+ clientId: authorization.clientId,
349
+ clientName: client?.clientName ?? null,
350
+ expiresAt: authorization.expiresAt.toISOString(),
351
+ redirectHost: new URL(authorization.redirectUri).host,
352
+ redirectUri: authorization.redirectUri,
353
+ requestId: authorization.requestId,
354
+ resource: authorization.resource ?? oauth.resource,
355
+ scope: authorization.scope ?? null,
356
+ },
357
+ });
358
+ }));
359
+ const decisionOpenApi = (operationId, summary) => (0, openApiBuilder_1.createOpenApiBuilder)(openApiOptions)
360
+ .withTags(["mcp"])
361
+ .withOperationId(operationId)
362
+ .withSummary(summary)
363
+ .withDescription("Called by the app's consent screen with the signed-in user's JWT. Returns the URL to send the browser to.")
364
+ .withPathParameter("request", { type: "string" })
365
+ .withResponse(200, {
366
+ data: {
367
+ properties: { redirectUrl: { type: "string" } },
368
+ type: "object",
369
+ },
370
+ })
371
+ .build();
372
+ app.post("/oauth/authorize/:request/approve", [
373
+ ...consentGuards,
374
+ decisionOpenApi("approveMcpOAuthRequest", "Approve a pending MCP OAuth request"),
375
+ ], (0, api_1.asyncHandler)(async (req, res) => {
376
+ const user = requireUser(req);
377
+ const pending = await loadPendingAuthorization(String(req.params.request));
378
+ const code = (0, mcpOAuthToken_1.generateMcpOAuthSecret)();
379
+ const now = luxon_1.DateTime.now();
380
+ const codeExpiresAt = now.plus({ seconds: oauth.authorizationCodeTtlSeconds });
381
+ const expiresAt = luxon_1.DateTime.max(luxon_1.DateTime.fromJSDate(pending.expiresAt), codeExpiresAt.plus({ seconds: USED_CODE_RETENTION_SECONDS }));
382
+ const approved = await mcpOAuthAuthorization_1.McpOAuthAuthorization.findOneAndUpdate({ _id: pending._id, status: "pending" }, {
383
+ $set: {
384
+ codeExpiresAt: codeExpiresAt.toJSDate(),
385
+ codeHash: (0, mcpOAuthToken_1.hashMcpOAuthSecret)(code),
386
+ expiresAt: expiresAt.toJSDate(),
387
+ status: "approved",
388
+ tokenEpoch: (0, auth_2.userTokenEpoch)(user),
389
+ userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
390
+ },
391
+ }, { returnDocument: "after" });
392
+ if (!approved) {
393
+ throw new errors_1.ConflictError({
394
+ code: "mcp-oauth-request-decided",
395
+ title: "Authorization request was already decided",
396
+ });
397
+ }
398
+ logger_1.logger.info("[MCPOAuth] Authorization approved", {
399
+ clientId: approved.clientId,
400
+ userId: String(user._id),
401
+ });
402
+ return res.json({
403
+ data: {
404
+ redirectUrl: appendParams(approved.redirectUri, {
405
+ code,
406
+ iss: oauth.issuer,
407
+ state: approved.state,
408
+ }),
409
+ },
410
+ });
411
+ }));
412
+ app.post("/oauth/authorize/:request/deny", [...consentGuards, decisionOpenApi("denyMcpOAuthRequest", "Deny a pending MCP OAuth request")], (0, api_1.asyncHandler)(async (req, res) => {
413
+ const user = requireUser(req);
414
+ const pending = await loadPendingAuthorization(String(req.params.request));
415
+ const denied = await mcpOAuthAuthorization_1.McpOAuthAuthorization.findOneAndUpdate({ _id: pending._id, status: "pending" }, {
416
+ $set: {
417
+ status: "denied",
418
+ userId: new mongoose_1.default.Types.ObjectId(String(user._id)),
419
+ },
420
+ }, { returnDocument: "after" });
421
+ if (!denied) {
422
+ throw new errors_1.ConflictError({
423
+ code: "mcp-oauth-request-decided",
424
+ title: "Authorization request was already decided",
425
+ });
426
+ }
427
+ return res.json({
428
+ data: {
429
+ redirectUrl: appendParams(denied.redirectUri, {
430
+ error: "access_denied",
431
+ error_description: "The user denied the request",
432
+ iss: oauth.issuer,
433
+ state: denied.state,
434
+ }),
435
+ },
436
+ });
437
+ }));
438
+ };
439
+ const exchangeAuthorizationCode = async (body, clientId, oauth, userModel) => {
440
+ const code = stringParam(body.code);
441
+ const redirectUri = stringParam(body.redirect_uri);
442
+ const codeVerifier = stringParam(body.code_verifier);
443
+ if (!code || !redirectUri || !codeVerifier) {
444
+ throw new OAuthProtocolError("invalid_request", "code, redirect_uri, and code_verifier are required");
445
+ }
446
+ const codeHash = (0, mcpOAuthToken_1.hashMcpOAuthSecret)(code);
447
+ const now = luxon_1.DateTime.now();
448
+ // Consume the code before checking it, so a failed attempt (wrong verifier) burns it too.
449
+ // The family id is fixed here so a replay can revoke it before the tokens exist.
450
+ const consumed = await mcpOAuthAuthorization_1.McpOAuthAuthorization.findOneAndUpdate({ codeHash, status: "approved" }, {
451
+ $set: {
452
+ expiresAt: now.plus({ seconds: USED_CODE_RETENTION_SECONDS }).toJSDate(),
453
+ familyId: (0, node_crypto_1.randomUUID)(),
454
+ status: "used",
455
+ usedAt: now.toJSDate(),
456
+ },
457
+ }, { returnDocument: "after" });
458
+ if (!consumed) {
459
+ const replayed = await mcpOAuthAuthorization_1.McpOAuthAuthorization.findOneOrNone({ codeHash });
460
+ if (replayed?.status === "used" && replayed.familyId) {
461
+ // RFC 6749 §4.1.2: a replayed code revokes the tokens it already issued.
462
+ logger_1.logger.warn("[MCPOAuth] Authorization code replayed, revoking its tokens", {
463
+ clientId: replayed.clientId,
464
+ });
465
+ await mcpOAuthToken_1.McpOAuthToken.revokeFamily(replayed.familyId);
466
+ }
467
+ throw new OAuthProtocolError("invalid_grant", "Authorization code is invalid or already used");
468
+ }
469
+ if (!consumed.codeExpiresAt || luxon_1.DateTime.fromJSDate(consumed.codeExpiresAt) <= now) {
470
+ throw new OAuthProtocolError("invalid_grant", "Authorization code expired");
471
+ }
472
+ if (consumed.clientId !== clientId || consumed.redirectUri !== redirectUri) {
473
+ throw new OAuthProtocolError("invalid_grant", "Authorization code was issued to another client or redirect_uri");
474
+ }
475
+ if (!CODE_VERIFIER_PATTERN.test(codeVerifier) ||
476
+ pkceS256(codeVerifier) !== consumed.codeChallenge) {
477
+ throw new OAuthProtocolError("invalid_grant", "code_verifier does not match the code_challenge");
478
+ }
479
+ const user = consumed.userId ? await userModel.findById(consumed.userId) : null;
480
+ if (!user || userIsDisabled(user)) {
481
+ throw new OAuthProtocolError("invalid_grant", "The authorizing user is not active");
482
+ }
483
+ if ((0, auth_2.isCredentialEpochStale)(consumed.tokenEpoch, user)) {
484
+ throw new OAuthProtocolError("invalid_grant", "The authorizing user's credentials changed after approval");
485
+ }
486
+ const issued = await issueOrInvalidGrant({
487
+ accessTokenTtlSeconds: oauth.accessTokenTtlSeconds,
488
+ clientId,
489
+ familyId: consumed.familyId,
490
+ refreshTokenTtlSeconds: oauth.refreshTokenTtlSeconds,
491
+ resource: consumed.resource,
492
+ scope: consumed.scope,
493
+ tokenEpoch: (0, auth_2.userTokenEpoch)(user),
494
+ userId: consumed.userId,
495
+ });
496
+ return {
497
+ access_token: issued.accessToken,
498
+ expires_in: oauth.accessTokenTtlSeconds,
499
+ refresh_token: issued.refreshToken,
500
+ scope: consumed.scope,
501
+ token_type: "Bearer",
502
+ };
503
+ };
504
+ const exchangeRefreshToken = async (body, clientId, oauth, userModel) => {
505
+ const refreshToken = stringParam(body.refresh_token);
506
+ if (!refreshToken) {
507
+ throw new OAuthProtocolError("invalid_request", "refresh_token is required");
508
+ }
509
+ const refreshTokenHash = (0, mcpOAuthToken_1.hashMcpOAuthSecret)(refreshToken);
510
+ const current = await mcpOAuthToken_1.McpOAuthToken.findOneOrNone({ refreshTokenHash });
511
+ if (!current || current.clientId !== clientId) {
512
+ throw new OAuthProtocolError("invalid_grant", "Refresh token is invalid");
513
+ }
514
+ const now = luxon_1.DateTime.now();
515
+ // Rotate atomically: only one exchange of a refresh token can win. The pre-rotate document
516
+ // tells this request whether it won, independent of what the earlier lookup saw.
517
+ const rotated = await mcpOAuthToken_1.McpOAuthToken.findOneAndUpdate({ _id: current._id, rotatedAt: { $exists: false } }, { $min: { revokedAt: now.toJSDate() }, $set: { rotatedAt: now.toJSDate() } }, { returnDocument: "before" });
518
+ if (!rotated) {
519
+ // A rotated refresh token came back: someone holds a copy. Kill the whole chain.
520
+ logger_1.logger.warn("[MCPOAuth] Refresh token reused, revoking its chain", {
521
+ clientId,
522
+ userId: String(current.userId),
523
+ });
524
+ await mcpOAuthToken_1.McpOAuthToken.revokeFamily(current.familyId);
525
+ throw new OAuthProtocolError("invalid_grant", "Refresh token is invalid, expired, or revoked");
526
+ }
527
+ if (rotated.revokedAt || luxon_1.DateTime.fromJSDate(rotated.refreshExpiresAt) <= now) {
528
+ throw new OAuthProtocolError("invalid_grant", "Refresh token is invalid, expired, or revoked");
529
+ }
530
+ const user = await userModel.findById(rotated.userId);
531
+ if (!user || userIsDisabled(user)) {
532
+ await mcpOAuthToken_1.McpOAuthToken.revokeFamily(rotated.familyId);
533
+ throw new OAuthProtocolError("invalid_grant", "The authorizing user is not active");
534
+ }
535
+ if ((0, auth_2.isCredentialEpochStale)(rotated.tokenEpoch, user)) {
536
+ // A password reset or session revocation ends every grant approved before it.
537
+ await mcpOAuthToken_1.McpOAuthToken.revokeFamily(rotated.familyId);
538
+ throw new OAuthProtocolError("invalid_grant", "The authorizing user's credentials changed after approval");
539
+ }
540
+ const issued = await issueOrInvalidGrant({
541
+ accessTokenTtlSeconds: oauth.accessTokenTtlSeconds,
542
+ clientId,
543
+ familyId: rotated.familyId,
544
+ refreshTokenTtlSeconds: oauth.refreshTokenTtlSeconds,
545
+ resource: rotated.resource,
546
+ scope: rotated.scope,
547
+ tokenEpoch: (0, auth_2.userTokenEpoch)(user),
548
+ userId: rotated.userId,
549
+ });
550
+ return {
551
+ access_token: issued.accessToken,
552
+ expires_in: oauth.accessTokenTtlSeconds,
553
+ refresh_token: issued.refreshToken,
554
+ scope: rotated.scope,
555
+ token_type: "Bearer",
556
+ };
557
+ };
558
+ const addTokenRoutes = (app, oauth, userModel) => {
559
+ app.post("/oauth/token", oauthHandler(async (req, res) => {
560
+ const body = (req.body ?? {});
561
+ const clientId = stringParam(body.client_id);
562
+ if (!clientId) {
563
+ throw new OAuthProtocolError("invalid_client", "client_id is required", 401);
564
+ }
565
+ const client = await mcpOAuthClient_1.McpOAuthClient.findOneOrNone({ clientId });
566
+ if (!client) {
567
+ throw new OAuthProtocolError("invalid_client", "Unknown client_id", 401);
568
+ }
569
+ const grantType = stringParam(body.grant_type);
570
+ if (!grantType || !client.grantTypes.includes(grantType)) {
571
+ throw new OAuthProtocolError("unsupported_grant_type", "grant_type must be authorization_code or refresh_token");
572
+ }
573
+ const tokens = grantType === "authorization_code"
574
+ ? await exchangeAuthorizationCode(body, clientId, oauth, userModel)
575
+ : await exchangeRefreshToken(body, clientId, oauth, userModel);
576
+ res.setHeader("Cache-Control", "no-store");
577
+ res.setHeader("Pragma", "no-cache");
578
+ (0, oauthMetadata_1.sendProtocolJson)(res, 200, tokens);
579
+ }));
580
+ app.post("/oauth/revoke", oauthHandler(async (req, res) => {
581
+ const body = (req.body ?? {});
582
+ const token = stringParam(body.token);
583
+ if (!token) {
584
+ throw new OAuthProtocolError("invalid_request", "token is required");
585
+ }
586
+ const tokenHash = (0, mcpOAuthToken_1.hashMcpOAuthSecret)(token);
587
+ const issued = await mcpOAuthToken_1.McpOAuthToken.findOneOrNone({
588
+ $or: [{ accessTokenHash: tokenHash }, { refreshTokenHash: tokenHash }],
589
+ });
590
+ const clientId = stringParam(body.client_id);
591
+ // RFC 7009 §2.2: unknown tokens and another client's tokens still get a 200.
592
+ if (issued && (!clientId || issued.clientId === clientId)) {
593
+ if (issued.refreshTokenHash === tokenHash) {
594
+ await mcpOAuthToken_1.McpOAuthToken.revokeFamily(issued.familyId);
595
+ }
596
+ else {
597
+ await mcpOAuthToken_1.McpOAuthToken.updateOne({ _id: issued._id, revokedAt: { $exists: false } }, { $set: { revokedAt: luxon_1.DateTime.now().toJSDate() } });
598
+ }
599
+ }
600
+ res.setHeader("Cache-Control", "no-store");
601
+ (0, oauthMetadata_1.sendProtocolJson)(res, 200, {});
602
+ }));
603
+ };
604
+ /**
605
+ * Mount the MCP OAuth authorization server: discovery documents, client registration (only with
606
+ * `dynamicClientRegistration`), authorize + consent decision, token, and revocation endpoints.
607
+ */
608
+ const addMcpOAuthRoutes = (app, options) => {
609
+ const { oauth, openApi, userModel } = options;
610
+ addDiscoveryRoutes(app, oauth);
611
+ if (oauth.dynamicClientRegistration) {
612
+ addRegistrationRoute(app, oauth);
613
+ }
614
+ addAuthorizeRoute(app, oauth);
615
+ addConsentRoutes(app, oauth, openApi);
616
+ addTokenRoutes(app, oauth, userModel);
617
+ };
618
+ exports.addMcpOAuthRoutes = addMcpOAuthRoutes;