@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
@@ -0,0 +1,1026 @@
1
+ import {beforeEach, describe, expect, it, spyOn} from "bun:test";
2
+ import {createHash, randomBytes} from "node:crypto";
3
+ import type express from "express";
4
+ import {DateTime} from "luxon";
5
+ import mongoose, {model, Schema} from "mongoose";
6
+ import supertest from "supertest";
7
+ import type TestAgent from "supertest/lib/agent";
8
+
9
+ import {modelRouter} from "../api";
10
+ import type {UserModel as UserModelType} from "../auth";
11
+ import {AuthToken} from "../authTokens";
12
+ import {McpOAuthAuthorization} from "../models/mcpOAuthAuthorization";
13
+ import {McpOAuthClient} from "../models/mcpOAuthClient";
14
+ import {McpOAuthToken} from "../models/mcpOAuthToken";
15
+ import {McpServiceToken} from "../models/mcpServiceToken";
16
+ import {Permissions, requireOAuthScope} from "../permissions";
17
+ import {getCurrentRequestContext} from "../requestContext";
18
+ import {TerrenoApp} from "../terrenoApp";
19
+ import {authAsUser, setupDb, UserModel} from "../tests";
20
+ import {type McpOAuthOptions, resolveMcpOAuthOption} from "./oauthMetadata";
21
+ import {clearMCPRegistry} from "./registry";
22
+
23
+ const typedUserModel = UserModel as unknown as UserModelType;
24
+
25
+ const ISSUER = "https://api.example.com";
26
+ const CONSENT_URL = "https://app.example.com/oauth/consent?theme=dark";
27
+ const REDIRECT_URI = "https://claude.ai/api/mcp/auth_callback";
28
+ const RESOURCE_METADATA_URL = `${ISSUER}/.well-known/oauth-protected-resource/mcp`;
29
+
30
+ const oauthOptions: McpOAuthOptions = {
31
+ allowedRedirectHosts: ["claude.ai", "*.chatgpt.com", "localhost"],
32
+ consentUrl: CONSENT_URL,
33
+ dynamicClientRegistration: true,
34
+ enabled: true,
35
+ issuer: ISSUER,
36
+ };
37
+
38
+ const noteSchema = new Schema({title: {description: "Note title", type: String}});
39
+ const OAuthNote =
40
+ (mongoose.models.OAuthNote as mongoose.Model<{title?: string}> | undefined) ??
41
+ model<{title?: string}>("OAuthNote", noteSchema);
42
+
43
+ const noteRouter = () =>
44
+ modelRouter("/oauth-notes", OAuthNote, {
45
+ collectionActions: {
46
+ whoami: {
47
+ handler: async ({user}) => ({
48
+ credential: getCurrentRequestContext()?.credential ?? null,
49
+ userId: String(user?._id),
50
+ }),
51
+ mcp: {name: "oauth_whoami"},
52
+ method: "GET",
53
+ permissions: [Permissions.IsAuthenticated],
54
+ },
55
+ },
56
+ permissions: {
57
+ create: [],
58
+ delete: [],
59
+ list: [Permissions.IsAuthenticated],
60
+ read: [Permissions.IsAuthenticated],
61
+ update: [],
62
+ },
63
+ });
64
+
65
+ const buildApp = (
66
+ {mcpOAuth}: {mcpOAuth?: McpOAuthOptions} = {mcpOAuth: oauthOptions}
67
+ ): express.Application =>
68
+ new TerrenoApp({
69
+ mcpOAuth,
70
+ mcpServiceTokens: true,
71
+ skipListen: true,
72
+ userModel: typedUserModel,
73
+ })
74
+ .register(noteRouter())
75
+ .build();
76
+
77
+ const createPkce = (): {challenge: string; verifier: string} => {
78
+ const verifier = randomBytes(32).toString("base64url");
79
+ return {challenge: createHash("sha256").update(verifier).digest("base64url"), verifier};
80
+ };
81
+
82
+ const whoamiCall = {
83
+ id: 1,
84
+ jsonrpc: "2.0",
85
+ method: "tools/call",
86
+ params: {arguments: {}, name: "oauth_whoami"},
87
+ };
88
+
89
+ const callMcp = (app: express.Application, bearer?: string) => {
90
+ const request = supertest(app).post("/mcp").set("accept", "application/json, text/event-stream");
91
+ if (bearer) {
92
+ request.set("Authorization", `Bearer ${bearer}`);
93
+ }
94
+ return request.send(whoamiCall);
95
+ };
96
+
97
+ const toolPayload = (text: string): Record<string, unknown> => {
98
+ const dataLine = text.split("\n").find((line) => line.startsWith("data:"));
99
+ const rpc = JSON.parse(dataLine ? dataLine.slice("data:".length) : text);
100
+ return JSON.parse(rpc.result.content[0].text);
101
+ };
102
+
103
+ const registerClient = async (
104
+ app: express.Application,
105
+ redirectUris: string[] = [REDIRECT_URI]
106
+ ): Promise<string> => {
107
+ const res = await supertest(app)
108
+ .post("/oauth/register")
109
+ .send({client_name: "Claude", redirect_uris: redirectUris});
110
+ expect(res.status).toBe(201);
111
+ return res.body.client_id as string;
112
+ };
113
+
114
+ const startAuthorization = (
115
+ app: express.Application,
116
+ params: Record<string, string>
117
+ ): supertest.Test => supertest(app).get("/oauth/authorize").query(params);
118
+
119
+ const requestIdFrom = (location: string): string =>
120
+ new URL(location).searchParams.get("request") as string;
121
+
122
+ interface Flow {
123
+ clientId: string;
124
+ code: string;
125
+ verifier: string;
126
+ }
127
+
128
+ /** Register, authorize, and approve; returns an authorization code ready to exchange. */
129
+ const approvedCode = async (app: express.Application, agent: TestAgent): Promise<Flow> => {
130
+ const clientId = await registerClient(app);
131
+ const {challenge, verifier} = createPkce();
132
+ const authorize = await startAuthorization(app, {
133
+ client_id: clientId,
134
+ code_challenge: challenge,
135
+ code_challenge_method: "S256",
136
+ redirect_uri: REDIRECT_URI,
137
+ response_type: "code",
138
+ state: "state-123",
139
+ });
140
+ const approve = await agent.post(
141
+ `/oauth/authorize/${requestIdFrom(authorize.headers.location)}/approve`
142
+ );
143
+ expect(approve.status).toBe(200);
144
+ const redirect = new URL(approve.body.data.redirectUrl);
145
+ return {clientId, code: redirect.searchParams.get("code") as string, verifier};
146
+ };
147
+
148
+ const exchangeCode = (app: express.Application, flow: Flow, overrides = {}) =>
149
+ supertest(app)
150
+ .post("/oauth/token")
151
+ .type("form")
152
+ .send({
153
+ client_id: flow.clientId,
154
+ code: flow.code,
155
+ code_verifier: flow.verifier,
156
+ grant_type: "authorization_code",
157
+ redirect_uri: REDIRECT_URI,
158
+ ...overrides,
159
+ });
160
+
161
+ const refresh = (app: express.Application, clientId: string, refreshToken: string) =>
162
+ supertest(app).post("/oauth/token").type("form").send({
163
+ client_id: clientId,
164
+ grant_type: "refresh_token",
165
+ refresh_token: refreshToken,
166
+ });
167
+
168
+ describe("MCP OAuth authorization server", () => {
169
+ let app: express.Application;
170
+ let agent: TestAgent;
171
+ let notAdminId: mongoose.Types.ObjectId;
172
+
173
+ beforeEach(async () => {
174
+ const [, notAdmin] = await setupDb();
175
+ notAdminId = notAdmin._id as mongoose.Types.ObjectId;
176
+ await Promise.all([
177
+ McpOAuthAuthorization.deleteMany({}),
178
+ McpOAuthClient.deleteMany({}),
179
+ McpOAuthToken.deleteMany({}),
180
+ McpServiceToken.deleteMany({}),
181
+ ]);
182
+ clearMCPRegistry();
183
+ app = buildApp();
184
+ agent = await authAsUser(app, "notAdmin");
185
+ });
186
+
187
+ describe("discovery", () => {
188
+ it("serves RFC 9728 protected-resource metadata at both well-known paths", async () => {
189
+ const root = await supertest(app).get("/.well-known/oauth-protected-resource");
190
+ const suffixed = await supertest(app).get("/.well-known/oauth-protected-resource/mcp");
191
+
192
+ expect(suffixed.body).toEqual(root.body);
193
+ expect(root.body).not.toHaveProperty("requestId");
194
+ expect(root.body).toMatchObject({
195
+ authorization_servers: [ISSUER],
196
+ bearer_methods_supported: ["header"],
197
+ resource: `${ISSUER}/mcp`,
198
+ });
199
+ });
200
+
201
+ it("serves RFC 8414 authorization-server metadata", async () => {
202
+ const res = await supertest(app).get("/.well-known/oauth-authorization-server");
203
+
204
+ expect(res.body).toMatchObject({
205
+ authorization_endpoint: `${ISSUER}/oauth/authorize`,
206
+ code_challenge_methods_supported: ["S256"],
207
+ grant_types_supported: ["authorization_code", "refresh_token"],
208
+ issuer: ISSUER,
209
+ registration_endpoint: `${ISSUER}/oauth/register`,
210
+ response_types_supported: ["code"],
211
+ revocation_endpoint: `${ISSUER}/oauth/revoke`,
212
+ token_endpoint: `${ISSUER}/oauth/token`,
213
+ token_endpoint_auth_methods_supported: ["none"],
214
+ });
215
+ });
216
+ });
217
+
218
+ describe("dynamic client registration", () => {
219
+ it("rejects a redirect URI outside allowedRedirectHosts", async () => {
220
+ const res = await supertest(app)
221
+ .post("/oauth/register")
222
+ .send({redirect_uris: ["https://evil.example/callback"]});
223
+
224
+ expect(res.status).toBe(400);
225
+ expect(res.body.error).toBe("invalid_redirect_uri");
226
+ });
227
+
228
+ it("rejects http redirects except on loopback hosts", async () => {
229
+ const insecure = await supertest(app)
230
+ .post("/oauth/register")
231
+ .send({redirect_uris: ["http://claude.ai/callback"]});
232
+ const loopback = await supertest(app)
233
+ .post("/oauth/register")
234
+ .send({redirect_uris: ["http://localhost:33418/callback"]});
235
+
236
+ expect(insecure.body.error).toBe("invalid_redirect_uri");
237
+ expect(loopback.status).toBe(201);
238
+ });
239
+
240
+ it("matches wildcard subdomains but not the bare domain", async () => {
241
+ const sub = await supertest(app)
242
+ .post("/oauth/register")
243
+ .send({redirect_uris: ["https://connectors.chatgpt.com/callback"]});
244
+ const bare = await supertest(app)
245
+ .post("/oauth/register")
246
+ .send({redirect_uris: ["https://chatgpt.com/callback"]});
247
+
248
+ expect(sub.status).toBe(201);
249
+ expect(bare.body.error).toBe("invalid_redirect_uri");
250
+ });
251
+
252
+ it("rejects confidential clients", async () => {
253
+ const res = await supertest(app)
254
+ .post("/oauth/register")
255
+ .send({
256
+ redirect_uris: [REDIRECT_URI],
257
+ token_endpoint_auth_method: "client_secret_basic",
258
+ });
259
+
260
+ expect(res.status).toBe(400);
261
+ expect(res.body.error).toBe("invalid_client_metadata");
262
+ });
263
+
264
+ it("registers a public client", async () => {
265
+ const res = await supertest(app)
266
+ .post("/oauth/register")
267
+ .send({client_name: "Claude", redirect_uris: [REDIRECT_URI]});
268
+
269
+ expect(res.status).toBe(201);
270
+ expect(res.body).toMatchObject({
271
+ client_name: "Claude",
272
+ grant_types: ["authorization_code", "refresh_token"],
273
+ redirect_uris: [REDIRECT_URI],
274
+ token_endpoint_auth_method: "none",
275
+ });
276
+ expect(res.body.client_id).toBeString();
277
+ });
278
+ });
279
+
280
+ describe("authorization code flow", () => {
281
+ it("issues access and refresh tokens that call /mcp as the approving user", async () => {
282
+ const clientId = await registerClient(app);
283
+ const {challenge, verifier} = createPkce();
284
+ const authorize = await startAuthorization(app, {
285
+ client_id: clientId,
286
+ code_challenge: challenge,
287
+ code_challenge_method: "S256",
288
+ redirect_uri: REDIRECT_URI,
289
+ resource: `${ISSUER}/mcp`,
290
+ response_type: "code",
291
+ state: "state-123",
292
+ });
293
+
294
+ expect(authorize.status).toBe(302);
295
+ const consent = new URL(authorize.headers.location);
296
+ expect(`${consent.origin}${consent.pathname}`).toBe("https://app.example.com/oauth/consent");
297
+ expect(consent.searchParams.get("theme")).toBe("dark");
298
+ const requestId = consent.searchParams.get("request") as string;
299
+
300
+ const pending = await agent.get(`/oauth/authorize/${requestId}`);
301
+ expect(pending.body.data).toMatchObject({
302
+ clientName: "Claude",
303
+ redirectHost: "claude.ai",
304
+ scope: "mcp",
305
+ });
306
+
307
+ const approve = await agent.post(`/oauth/authorize/${requestId}/approve`);
308
+ const redirect = new URL(approve.body.data.redirectUrl);
309
+ expect(`${redirect.origin}${redirect.pathname}`).toBe(REDIRECT_URI);
310
+ expect(redirect.searchParams.get("state")).toBe("state-123");
311
+ expect(redirect.searchParams.get("iss")).toBe(ISSUER);
312
+
313
+ const token = await exchangeCode(app, {
314
+ clientId,
315
+ code: redirect.searchParams.get("code") as string,
316
+ verifier,
317
+ });
318
+
319
+ expect(token.status).toBe(200);
320
+ expect(token.headers["cache-control"]).toBe("no-store");
321
+ expect(token.body).toMatchObject({expires_in: 3600, scope: "mcp", token_type: "Bearer"});
322
+ expect(token.body.access_token).toStartWith("mcpat_");
323
+ expect(token.body.refresh_token).toStartWith("mcprt_");
324
+
325
+ const mcp = await callMcp(app, token.body.access_token);
326
+ expect(toolPayload(mcp.text)).toEqual({credential: "oauth", userId: String(notAdminId)});
327
+ });
328
+
329
+ it("redirects with invalid_request for plain PKCE", async () => {
330
+ const clientId = await registerClient(app);
331
+ const {verifier} = createPkce();
332
+
333
+ const res = await startAuthorization(app, {
334
+ client_id: clientId,
335
+ code_challenge: verifier,
336
+ code_challenge_method: "plain",
337
+ redirect_uri: REDIRECT_URI,
338
+ response_type: "code",
339
+ state: "s",
340
+ });
341
+
342
+ const redirect = new URL(res.headers.location);
343
+ expect(`${redirect.origin}${redirect.pathname}`).toBe(REDIRECT_URI);
344
+ expect(redirect.searchParams.get("error")).toBe("invalid_request");
345
+ expect(redirect.searchParams.get("state")).toBe("s");
346
+ });
347
+
348
+ it("answers in place, without redirecting, for an unregistered redirect_uri", async () => {
349
+ const clientId = await registerClient(app);
350
+ const {challenge} = createPkce();
351
+
352
+ const res = await startAuthorization(app, {
353
+ client_id: clientId,
354
+ code_challenge: challenge,
355
+ code_challenge_method: "S256",
356
+ redirect_uri: "https://claude.ai/other",
357
+ response_type: "code",
358
+ });
359
+
360
+ expect(res.status).toBe(400);
361
+ expect(res.body.error).toBe("invalid_request");
362
+ });
363
+
364
+ it("rejects a wrong code_verifier and burns the code", async () => {
365
+ const flow = await approvedCode(app, agent);
366
+
367
+ const wrong = await exchangeCode(app, flow, {code_verifier: createPkce().verifier});
368
+ const retry = await exchangeCode(app, flow);
369
+
370
+ expect(wrong.status).toBe(400);
371
+ expect(wrong.body.error).toBe("invalid_grant");
372
+ expect(retry.body.error).toBe("invalid_grant");
373
+ });
374
+
375
+ it("rejects a reused code and revokes the tokens it issued", async () => {
376
+ const flow = await approvedCode(app, agent);
377
+ const first = await exchangeCode(app, flow);
378
+
379
+ const reuse = await exchangeCode(app, flow);
380
+ const mcp = await callMcp(app, first.body.access_token);
381
+
382
+ expect(reuse.status).toBe(400);
383
+ expect(reuse.body.error).toBe("invalid_grant");
384
+ expect(mcp.status).toBe(401);
385
+ });
386
+
387
+ it("revokes every token when a code is exchanged twice at once", async () => {
388
+ const flow = await approvedCode(app, agent);
389
+
390
+ const results = await Promise.all([exchangeCode(app, flow), exchangeCode(app, flow)]);
391
+
392
+ // Depending on interleaving the winner may also lose its pair; it never keeps one.
393
+ expect(results.filter((res) => res.status === 200).length).toBeLessThanOrEqual(1);
394
+ expect(results.some((res) => res.body.error === "invalid_grant")).toBe(true);
395
+ expect(await McpOAuthToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
396
+ });
397
+
398
+ it("revokes the tokens when a code is replayed after issue but before the exchange returns", async () => {
399
+ const flow = await approvedCode(app, agent);
400
+ const realIssue = McpOAuthToken.issue.bind(McpOAuthToken);
401
+ let replay: supertest.Response | undefined;
402
+ const issueSpy = spyOn(McpOAuthToken, "issue").mockImplementation(async (options) => {
403
+ const issued = await realIssue(options);
404
+ replay = await exchangeCode(app, flow);
405
+ return issued;
406
+ });
407
+ let first: supertest.Response;
408
+ try {
409
+ first = await exchangeCode(app, flow);
410
+ } finally {
411
+ issueSpy.mockRestore();
412
+ }
413
+
414
+ expect(replay?.body.error).toBe("invalid_grant");
415
+ expect((await callMcp(app, first.body.access_token)).status).toBe(401);
416
+ expect((await refresh(app, flow.clientId, first.body.refresh_token)).body.error).toBe(
417
+ "invalid_grant"
418
+ );
419
+ });
420
+
421
+ it("refuses to issue tokens when the code is replayed before they are issued", async () => {
422
+ const flow = await approvedCode(app, agent);
423
+ const realIssue = McpOAuthToken.issue.bind(McpOAuthToken);
424
+ let replay: supertest.Response | undefined;
425
+ const issueSpy = spyOn(McpOAuthToken, "issue").mockImplementation(async (options) => {
426
+ replay = await exchangeCode(app, flow);
427
+ return realIssue(options);
428
+ });
429
+ let first: supertest.Response;
430
+ try {
431
+ first = await exchangeCode(app, flow);
432
+ } finally {
433
+ issueSpy.mockRestore();
434
+ }
435
+
436
+ expect(replay?.body.error).toBe("invalid_grant");
437
+ expect(first.status).toBe(400);
438
+ expect(first.body.error).toBe("invalid_grant");
439
+ expect(await McpOAuthToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
440
+ });
441
+
442
+ it("rejects approving an expired pending request", async () => {
443
+ const clientId = await registerClient(app);
444
+ const authorize = await startAuthorization(app, {
445
+ client_id: clientId,
446
+ code_challenge: createPkce().challenge,
447
+ code_challenge_method: "S256",
448
+ response_type: "code",
449
+ });
450
+ const requestId = requestIdFrom(authorize.headers.location);
451
+ await McpOAuthAuthorization.updateOne(
452
+ {requestId},
453
+ {$set: {expiresAt: DateTime.now().minus({minutes: 1}).toJSDate()}}
454
+ );
455
+
456
+ const res = await agent.post(`/oauth/authorize/${requestId}/approve`);
457
+
458
+ expect(res.status).toBe(400);
459
+ expect(res.body.title).toBe("Authorization request expired");
460
+ });
461
+
462
+ it("rejects an expired authorization code", async () => {
463
+ const flow = await approvedCode(app, agent);
464
+ await McpOAuthAuthorization.updateMany(
465
+ {},
466
+ {$set: {codeExpiresAt: DateTime.now().minus({seconds: 1}).toJSDate()}}
467
+ );
468
+
469
+ const res = await exchangeCode(app, flow);
470
+
471
+ expect(res.body.error).toBe("invalid_grant");
472
+ });
473
+
474
+ it("redirects with access_denied when the user denies", async () => {
475
+ const clientId = await registerClient(app);
476
+ const authorize = await startAuthorization(app, {
477
+ client_id: clientId,
478
+ code_challenge: createPkce().challenge,
479
+ code_challenge_method: "S256",
480
+ response_type: "code",
481
+ state: "deny-state",
482
+ });
483
+ const requestId = requestIdFrom(authorize.headers.location);
484
+
485
+ const deny = await agent.post(`/oauth/authorize/${requestId}/deny`);
486
+ const approveAfter = await agent.post(`/oauth/authorize/${requestId}/approve`);
487
+
488
+ const redirect = new URL(deny.body.data.redirectUrl);
489
+ expect(redirect.searchParams.get("error")).toBe("access_denied");
490
+ expect(redirect.searchParams.get("state")).toBe("deny-state");
491
+ expect(approveAfter.status).toBe(409);
492
+ });
493
+
494
+ it("refuses delegated MCP credentials on the consent endpoints", async () => {
495
+ const flow = await approvedCode(app, agent);
496
+ const {access_token: accessToken} = (await exchangeCode(app, flow)).body;
497
+ const clientId = await registerClient(app);
498
+ const authorize = await startAuthorization(app, {
499
+ client_id: clientId,
500
+ code_challenge: createPkce().challenge,
501
+ code_challenge_method: "S256",
502
+ response_type: "code",
503
+ });
504
+
505
+ const res = await supertest(app)
506
+ .post(`/oauth/authorize/${requestIdFrom(authorize.headers.location)}/approve`)
507
+ .set("Authorization", `Bearer ${accessToken}`);
508
+
509
+ expect(res.status).toBe(401);
510
+ });
511
+ });
512
+
513
+ describe("refresh tokens", () => {
514
+ it("rotates the refresh token on every exchange", async () => {
515
+ const flow = await approvedCode(app, agent);
516
+ const first = (await exchangeCode(app, flow)).body;
517
+
518
+ const second = await refresh(app, flow.clientId, first.refresh_token);
519
+
520
+ expect(second.status).toBe(200);
521
+ expect(second.body.refresh_token).not.toBe(first.refresh_token);
522
+ expect((await callMcp(app, second.body.access_token)).status).toBe(200);
523
+ expect((await callMcp(app, first.access_token)).status).toBe(401);
524
+ });
525
+
526
+ it("revokes the whole chain when a rotated refresh token is reused", async () => {
527
+ const flow = await approvedCode(app, agent);
528
+ const first = (await exchangeCode(app, flow)).body;
529
+ const second = (await refresh(app, flow.clientId, first.refresh_token)).body;
530
+
531
+ const reuse = await refresh(app, flow.clientId, first.refresh_token);
532
+ const third = await refresh(app, flow.clientId, second.refresh_token);
533
+
534
+ expect(reuse.body.error).toBe("invalid_grant");
535
+ expect(third.body.error).toBe("invalid_grant");
536
+ expect((await callMcp(app, second.access_token)).status).toBe(401);
537
+ });
538
+
539
+ it("revokes the whole chain when a refresh token is exchanged twice at once", async () => {
540
+ const flow = await approvedCode(app, agent);
541
+ const first = (await exchangeCode(app, flow)).body;
542
+
543
+ const results = await Promise.all([
544
+ refresh(app, flow.clientId, first.refresh_token),
545
+ refresh(app, flow.clientId, first.refresh_token),
546
+ ]);
547
+
548
+ // Depending on interleaving the winner may also lose its pair; it never keeps one.
549
+ expect(results.filter((res) => res.status === 200).length).toBeLessThanOrEqual(1);
550
+ expect(results.some((res) => res.body.error === "invalid_grant")).toBe(true);
551
+ expect(await McpOAuthToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
552
+ });
553
+
554
+ it("revokes the chain when two exchanges of one refresh token read it at the same time", async () => {
555
+ const flow = await approvedCode(app, agent);
556
+ const first = (await exchangeCode(app, flow)).body;
557
+ // Hold each lookup until both requests have read the token, so both start from the same state.
558
+ const realLookup = McpOAuthToken.findOneOrNone.bind(McpOAuthToken);
559
+ let lookups = 0;
560
+ let releaseLookups = (): void => {};
561
+ const bothLookedUp = new Promise<void>((resolve) => {
562
+ releaseLookups = resolve;
563
+ });
564
+ const lookupSpy = spyOn(McpOAuthToken, "findOneOrNone").mockImplementation((async (
565
+ ...args: Parameters<typeof realLookup>
566
+ ) => {
567
+ const found = await realLookup(...args);
568
+ lookups += 1;
569
+ if (lookups === 2) {
570
+ releaseLookups();
571
+ }
572
+ await bothLookedUp;
573
+ return found;
574
+ }) as typeof McpOAuthToken.findOneOrNone);
575
+ let responses: supertest.Response[];
576
+ try {
577
+ responses = await Promise.all([
578
+ refresh(app, flow.clientId, first.refresh_token),
579
+ refresh(app, flow.clientId, first.refresh_token),
580
+ ]);
581
+ } finally {
582
+ lookupSpy.mockRestore();
583
+ }
584
+
585
+ expect(responses.some((res) => res.body.error === "invalid_grant")).toBe(true);
586
+ for (const res of responses.filter((candidate) => candidate.status === 200)) {
587
+ expect((await callMcp(app, res.body.access_token)).status).toBe(401);
588
+ expect((await refresh(app, flow.clientId, res.body.refresh_token)).body.error).toBe(
589
+ "invalid_grant"
590
+ );
591
+ }
592
+ });
593
+
594
+ it("keeps the chain revoked when the winning exchange issues after the loser revoked it", async () => {
595
+ const flow = await approvedCode(app, agent);
596
+ const first = (await exchangeCode(app, flow)).body;
597
+ // The exchange that wins the rotation waits in issue until the losing exchange has answered.
598
+ const realIssue = McpOAuthToken.issue.bind(McpOAuthToken);
599
+ let markLoserDone = (): void => {};
600
+ const loserDone = new Promise<void>((resolve) => {
601
+ markLoserDone = resolve;
602
+ });
603
+ const issueSpy = spyOn(McpOAuthToken, "issue").mockImplementation(async (options) => {
604
+ await loserDone;
605
+ return realIssue(options);
606
+ });
607
+ let responses: supertest.Response[];
608
+ try {
609
+ responses = await Promise.all(
610
+ [0, 1].map(async () => {
611
+ const res = await refresh(app, flow.clientId, first.refresh_token);
612
+ markLoserDone();
613
+ return res;
614
+ })
615
+ );
616
+ } finally {
617
+ issueSpy.mockRestore();
618
+ }
619
+
620
+ expect(responses.map((res) => res.body.error)).toEqual(["invalid_grant", "invalid_grant"]);
621
+ expect(await McpOAuthToken.countDocuments({revokedAt: {$exists: false}})).toBe(0);
622
+ });
623
+ });
624
+
625
+ describe("revocation", () => {
626
+ it("revokes an access token and always answers 200", async () => {
627
+ const flow = await approvedCode(app, agent);
628
+ const {access_token: accessToken} = (await exchangeCode(app, flow)).body;
629
+
630
+ const res = await supertest(app)
631
+ .post("/oauth/revoke")
632
+ .type("form")
633
+ .send({client_id: flow.clientId, token: accessToken});
634
+ const unknown = await supertest(app)
635
+ .post("/oauth/revoke")
636
+ .type("form")
637
+ .send({token: "mcpat_unknown"});
638
+
639
+ expect(res.status).toBe(200);
640
+ expect(unknown.status).toBe(200);
641
+ expect((await callMcp(app, accessToken)).status).toBe(401);
642
+ });
643
+
644
+ it("revokes the chain when a refresh token is revoked", async () => {
645
+ const flow = await approvedCode(app, agent);
646
+ const tokens = (await exchangeCode(app, flow)).body;
647
+
648
+ await supertest(app).post("/oauth/revoke").send({token: tokens.refresh_token});
649
+
650
+ expect((await callMcp(app, tokens.access_token)).status).toBe(401);
651
+ expect((await refresh(app, flow.clientId, tokens.refresh_token)).body.error).toBe(
652
+ "invalid_grant"
653
+ );
654
+ });
655
+ });
656
+
657
+ describe("/mcp resource server", () => {
658
+ it("challenges a credential-less request with the resource metadata URL", async () => {
659
+ const res = await callMcp(app);
660
+
661
+ expect(res.status).toBe(401);
662
+ expect(res.headers["www-authenticate"]).toBe(
663
+ `Bearer resource_metadata="${RESOURCE_METADATA_URL}"`
664
+ );
665
+ });
666
+
667
+ it("marks a presented but rejected token as invalid_token", async () => {
668
+ const res = await callMcp(app, "mcpat_not-a-real-token");
669
+
670
+ expect(res.status).toBe(401);
671
+ expect(res.headers["www-authenticate"]).toContain('error="invalid_token"');
672
+ });
673
+
674
+ it("rejects an expired access token", async () => {
675
+ const flow = await approvedCode(app, agent);
676
+ const {access_token: accessToken} = (await exchangeCode(app, flow)).body;
677
+ await McpOAuthToken.updateMany(
678
+ {},
679
+ {$set: {accessExpiresAt: DateTime.now().minus({seconds: 1}).toJSDate()}}
680
+ );
681
+
682
+ expect((await callMcp(app, accessToken)).status).toBe(401);
683
+ });
684
+
685
+ it("rejects a disabled user's access token", async () => {
686
+ const flow = await approvedCode(app, agent);
687
+ const {access_token: accessToken} = (await exchangeCode(app, flow)).body;
688
+ await UserModel.updateOne({_id: notAdminId}, {$set: {disabled: true}});
689
+
690
+ expect((await callMcp(app, accessToken)).status).toBe(401);
691
+ });
692
+
693
+ it("keeps accepting JWT and mcp_ service tokens", async () => {
694
+ const created = await agent.post("/mcp/service-tokens").send({name: "Agent"});
695
+
696
+ const jwtCall = await agent
697
+ .post("/mcp")
698
+ .set("accept", "application/json, text/event-stream")
699
+ .send(whoamiCall);
700
+ const tokenCall = await callMcp(app, created.body.data.token);
701
+
702
+ expect(toolPayload(jwtCall.text).credential).toBe("jwt");
703
+ expect(toolPayload(tokenCall.text).credential).toBe("mcp-service-token");
704
+ });
705
+ });
706
+
707
+ describe("credential events", () => {
708
+ const resetPassword = async (): Promise<void> => {
709
+ const issued = await AuthToken.issueFor({_id: String(notAdminId)}, "passwordReset");
710
+ const res = await supertest(app)
711
+ .post("/auth/resetPassword")
712
+ .send({password: "reset-password-123", token: issued.token});
713
+ expect(res.status).toBe(200);
714
+ };
715
+
716
+ it("ends service tokens, access tokens, and refresh tokens issued before a password reset", async () => {
717
+ const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "Agent"})).body.data
718
+ .token as string;
719
+ const flow = await approvedCode(app, agent);
720
+ const oauth = (await exchangeCode(app, flow)).body;
721
+ expect((await callMcp(app, serviceToken)).status).toBe(200);
722
+ expect((await callMcp(app, oauth.access_token)).status).toBe(200);
723
+
724
+ await resetPassword();
725
+
726
+ const serviceCall = await callMcp(app, serviceToken);
727
+ expect(serviceCall.status).toBe(401);
728
+ expect(serviceCall.headers["www-authenticate"]).toContain('error="invalid_token"');
729
+ expect((await callMcp(app, oauth.access_token)).status).toBe(401);
730
+ const refreshed = await refresh(app, flow.clientId, oauth.refresh_token);
731
+ expect(refreshed.status).toBe(400);
732
+ expect(refreshed.body.error).toBe("invalid_grant");
733
+ });
734
+
735
+ it("lists service tokens from before a password reset as revoked", async () => {
736
+ await agent.post("/mcp/service-tokens").send({name: "Before reset"});
737
+
738
+ await resetPassword();
739
+
740
+ const list = await agent.get("/mcp/service-tokens");
741
+ expect(list.body.data).toHaveLength(1);
742
+ expect(list.body.data[0].revokedAt).not.toBeNull();
743
+ });
744
+
745
+ it("refuses to exchange a code approved before a password reset", async () => {
746
+ const flow = await approvedCode(app, agent);
747
+
748
+ await resetPassword();
749
+
750
+ const exchanged = await exchangeCode(app, flow);
751
+ expect(exchanged.status).toBe(400);
752
+ expect(exchanged.body.error).toBe("invalid_grant");
753
+ });
754
+
755
+ it("ends MCP credentials on any tokenEpoch bump, such as a Better Auth session revocation", async () => {
756
+ const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "Agent"})).body.data
757
+ .token as string;
758
+ const flow = await approvedCode(app, agent);
759
+ const oauth = (await exchangeCode(app, flow)).body;
760
+
761
+ await UserModel.updateOne({_id: notAdminId}, {$inc: {tokenEpoch: 1}});
762
+
763
+ expect((await callMcp(app, serviceToken)).status).toBe(401);
764
+ expect((await callMcp(app, oauth.access_token)).status).toBe(401);
765
+ expect((await refresh(app, flow.clientId, oauth.refresh_token)).body.error).toBe(
766
+ "invalid_grant"
767
+ );
768
+ });
769
+
770
+ it("accepts MCP credentials issued after a password reset", async () => {
771
+ await resetPassword();
772
+
773
+ const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "After"})).body.data
774
+ .token as string;
775
+ const flow = await approvedCode(app, agent);
776
+ const oauth = (await exchangeCode(app, flow)).body;
777
+ const refreshed = await refresh(app, flow.clientId, oauth.refresh_token);
778
+
779
+ expect((await callMcp(app, serviceToken)).status).toBe(200);
780
+ expect(refreshed.status).toBe(200);
781
+ expect((await callMcp(app, refreshed.body.access_token)).status).toBe(200);
782
+ });
783
+ });
784
+
785
+ it("documents the consent endpoints in OpenAPI", async () => {
786
+ const res = await supertest(app).get("/openapi.json");
787
+
788
+ expect(res.body.paths["/oauth/authorize/{request}/approve"].post.operationId).toBe(
789
+ "approveMcpOAuthRequest"
790
+ );
791
+ });
792
+ });
793
+
794
+ describe("MCP OAuth granted scopes", () => {
795
+ let app: express.Application;
796
+ let agent: TestAgent;
797
+
798
+ const scopedRouter = () =>
799
+ modelRouter("/scoped-notes", OAuthNote, {
800
+ collectionActions: {
801
+ scopes: {
802
+ handler: async () => ({scopes: getCurrentRequestContext()?.oauthScopes ?? null}),
803
+ mcp: {name: "scoped_scopes"},
804
+ method: "GET",
805
+ permissions: [Permissions.IsAuthenticated],
806
+ },
807
+ write: {
808
+ handler: async () => ({written: true}),
809
+ mcp: {name: "scoped_write"},
810
+ method: "POST",
811
+ permissions: [Permissions.IsAuthenticated, requireOAuthScope("write")],
812
+ },
813
+ },
814
+ permissions: {create: [], delete: [], list: [], read: [], update: []},
815
+ });
816
+
817
+ const callTool = (bearer: string, name: string) =>
818
+ supertest(app)
819
+ .post("/mcp")
820
+ .set("accept", "application/json, text/event-stream")
821
+ .set("Authorization", `Bearer ${bearer}`)
822
+ .send({id: 1, jsonrpc: "2.0", method: "tools/call", params: {arguments: {}, name}});
823
+
824
+ const rpcResult = (text: string): {content: {text: string}[]; isError?: boolean} => {
825
+ const dataLine = text.split("\n").find((line) => line.startsWith("data:"));
826
+ return JSON.parse(dataLine ? dataLine.slice("data:".length) : text).result;
827
+ };
828
+
829
+ const tokenWithScope = async (scope: string): Promise<string> => {
830
+ const clientId = await registerClient(app);
831
+ const {challenge, verifier} = createPkce();
832
+ const authorize = await startAuthorization(app, {
833
+ client_id: clientId,
834
+ code_challenge: challenge,
835
+ code_challenge_method: "S256",
836
+ redirect_uri: REDIRECT_URI,
837
+ response_type: "code",
838
+ scope,
839
+ });
840
+ const approve = await agent.post(
841
+ `/oauth/authorize/${requestIdFrom(authorize.headers.location)}/approve`
842
+ );
843
+ const code = new URL(approve.body.data.redirectUrl).searchParams.get("code") as string;
844
+ const token = await exchangeCode(app, {clientId, code, verifier});
845
+ expect(token.body.scope).toBe(scope);
846
+ return token.body.access_token as string;
847
+ };
848
+
849
+ beforeEach(async () => {
850
+ await setupDb();
851
+ await Promise.all([
852
+ McpOAuthAuthorization.deleteMany({}),
853
+ McpOAuthClient.deleteMany({}),
854
+ McpOAuthToken.deleteMany({}),
855
+ McpServiceToken.deleteMany({}),
856
+ ]);
857
+ clearMCPRegistry();
858
+ app = new TerrenoApp({
859
+ mcpOAuth: {...oauthOptions, scopesSupported: ["read", "write"]},
860
+ mcpServiceTokens: true,
861
+ skipListen: true,
862
+ userModel: typedUserModel,
863
+ })
864
+ .register(scopedRouter())
865
+ .build();
866
+ agent = await authAsUser(app, "notAdmin");
867
+ });
868
+
869
+ it("puts the token's granted scopes in the request context", async () => {
870
+ const token = await tokenWithScope("read");
871
+
872
+ const res = await callTool(token, "scoped_scopes");
873
+
874
+ expect(JSON.parse(rpcResult(res.text).content[0].text)).toEqual({scopes: ["read"]});
875
+ });
876
+
877
+ it("refuses a tool that requires a scope the token was not granted", async () => {
878
+ const readToken = await tokenWithScope("read");
879
+ const writeToken = await tokenWithScope("read write");
880
+
881
+ const denied = rpcResult((await callTool(readToken, "scoped_write")).text);
882
+ const allowed = rpcResult((await callTool(writeToken, "scoped_write")).text);
883
+
884
+ expect(denied.isError).toBe(true);
885
+ expect(JSON.parse(allowed.content[0].text)).toEqual({written: true});
886
+ });
887
+
888
+ it("does not apply OAuth scopes to the user's own JWT or service token", async () => {
889
+ const serviceToken = (await agent.post("/mcp/service-tokens").send({name: "Agent"})).body.data
890
+ .token as string;
891
+
892
+ const viaServiceToken = rpcResult((await callTool(serviceToken, "scoped_write")).text);
893
+ const viaScopes = rpcResult((await callTool(serviceToken, "scoped_scopes")).text);
894
+
895
+ expect(JSON.parse(viaServiceToken.content[0].text)).toEqual({written: true});
896
+ expect(JSON.parse(viaScopes.content[0].text)).toEqual({scopes: null});
897
+ });
898
+ });
899
+
900
+ describe("resolveMcpOAuthOption", () => {
901
+ it("returns undefined while disabled", () => {
902
+ expect(resolveMcpOAuthOption(undefined)).toBeUndefined();
903
+ expect(resolveMcpOAuthOption({...oauthOptions, enabled: false})).toBeUndefined();
904
+ });
905
+
906
+ it("fills defaults", () => {
907
+ expect(resolveMcpOAuthOption(oauthOptions)).toMatchObject({
908
+ accessTokenTtlSeconds: 3600,
909
+ issuer: ISSUER,
910
+ resource: `${ISSUER}/mcp`,
911
+ resourceMetadataUrl: RESOURCE_METADATA_URL,
912
+ scopesSupported: ["mcp"],
913
+ });
914
+ });
915
+
916
+ it("throws at boot for an issuer with a path or without https", () => {
917
+ expect(() => resolveMcpOAuthOption({...oauthOptions, issuer: `${ISSUER}/api`})).toThrow(
918
+ "MCP OAuth is misconfigured"
919
+ );
920
+ expect(() =>
921
+ resolveMcpOAuthOption({...oauthOptions, issuer: "http://api.example.com"})
922
+ ).toThrow("MCP OAuth is misconfigured");
923
+ });
924
+
925
+ it("throws at boot when registration is on without allowed redirect hosts", () => {
926
+ expect(() => resolveMcpOAuthOption({...oauthOptions, allowedRedirectHosts: []})).toThrow(
927
+ "MCP OAuth is misconfigured"
928
+ );
929
+ });
930
+
931
+ it("leaves dynamic client registration off unless asked for", () => {
932
+ const {allowedRedirectHosts: _hosts, dynamicClientRegistration: _dcr, ...rest} = oauthOptions;
933
+
934
+ expect(resolveMcpOAuthOption(rest)).toMatchObject({
935
+ allowedRedirectHosts: [],
936
+ dynamicClientRegistration: false,
937
+ });
938
+ });
939
+ });
940
+
941
+ describe("MCP OAuth opt-in", () => {
942
+ const oauthPaths: [string, string][] = [
943
+ ["get", "/.well-known/oauth-protected-resource"],
944
+ ["get", "/.well-known/oauth-protected-resource/mcp"],
945
+ ["get", "/.well-known/oauth-authorization-server"],
946
+ ["post", "/oauth/register"],
947
+ ["get", "/oauth/authorize"],
948
+ ["post", "/oauth/token"],
949
+ ["post", "/oauth/revoke"],
950
+ ];
951
+
952
+ beforeEach(async () => {
953
+ await setupDb();
954
+ await Promise.all([
955
+ McpOAuthAuthorization.deleteMany({}),
956
+ McpOAuthClient.deleteMany({}),
957
+ McpOAuthToken.deleteMany({}),
958
+ ]);
959
+ clearMCPRegistry();
960
+ });
961
+
962
+ it("mounts no OAuth routes, metadata, or /mcp challenge without mcpOAuth", async () => {
963
+ for (const mcpOAuth of [undefined, {...oauthOptions, enabled: false}]) {
964
+ const app = buildApp({mcpOAuth});
965
+
966
+ for (const [method, path] of oauthPaths) {
967
+ const res = await (method === "get" ? supertest(app).get(path) : supertest(app).post(path));
968
+ expect(`${method} ${path} ${res.status}`).toBe(`${method} ${path} 404`);
969
+ }
970
+ const mcp = await callMcp(app);
971
+ expect(mcp.status).not.toBe(401);
972
+ expect(mcp.headers["www-authenticate"]).toBeUndefined();
973
+ }
974
+ });
975
+
976
+ describe("with dynamic client registration off", () => {
977
+ let app: express.Application;
978
+ let agent: TestAgent;
979
+
980
+ beforeEach(async () => {
981
+ const {allowedRedirectHosts: _hosts, dynamicClientRegistration: _dcr, ...rest} = oauthOptions;
982
+ app = buildApp({mcpOAuth: rest});
983
+ agent = await authAsUser(app, "notAdmin");
984
+ });
985
+
986
+ it("answers /oauth/register with 404 and leaves it out of the metadata", async () => {
987
+ const register = await supertest(app)
988
+ .post("/oauth/register")
989
+ .send({client_name: "Anyone", redirect_uris: [REDIRECT_URI]});
990
+ const metadata = await supertest(app).get("/.well-known/oauth-authorization-server");
991
+
992
+ expect(register.status).toBe(404);
993
+ expect(await McpOAuthClient.countDocuments({})).toBe(0);
994
+ expect(metadata.status).toBe(200);
995
+ expect(metadata.body.registration_endpoint).toBeUndefined();
996
+ expect(metadata.body.token_endpoint).toBe(`${ISSUER}/oauth/token`);
997
+ });
998
+
999
+ it("still runs the flow for a client the app created", async () => {
1000
+ const client = await McpOAuthClient.create({
1001
+ clientId: "preconfigured-claude",
1002
+ clientName: "Claude",
1003
+ grantTypes: ["authorization_code", "refresh_token"],
1004
+ redirectUris: [REDIRECT_URI],
1005
+ responseTypes: ["code"],
1006
+ });
1007
+ const {challenge, verifier} = createPkce();
1008
+ const authorize = await startAuthorization(app, {
1009
+ client_id: client.clientId,
1010
+ code_challenge: challenge,
1011
+ code_challenge_method: "S256",
1012
+ redirect_uri: REDIRECT_URI,
1013
+ response_type: "code",
1014
+ });
1015
+ const approve = await agent.post(
1016
+ `/oauth/authorize/${requestIdFrom(authorize.headers.location)}/approve`
1017
+ );
1018
+ const code = new URL(approve.body.data.redirectUrl).searchParams.get("code") as string;
1019
+
1020
+ const tokens = await exchangeCode(app, {clientId: client.clientId, code, verifier});
1021
+
1022
+ expect(tokens.status).toBe(200);
1023
+ expect((await callMcp(app, tokens.body.access_token)).status).toBe(200);
1024
+ });
1025
+ });
1026
+ });