@terreno/api 58.0.6 → 58.1.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 (75) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/actions.d.ts +6 -0
  3. package/dist/api.d.ts +21 -0
  4. package/dist/api.js +57 -32
  5. package/dist/bulk.d.ts +79 -0
  6. package/dist/bulk.js +449 -0
  7. package/dist/bulkOpenApi.d.ts +15 -0
  8. package/dist/bulkOpenApi.js +103 -0
  9. package/dist/bulkTransaction.d.ts +33 -0
  10. package/dist/bulkTransaction.js +126 -0
  11. package/dist/errors.d.ts +2 -0
  12. package/dist/errors.js +8 -6
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.js +6 -3
  15. package/dist/mcp/actionTools.js +2 -0
  16. package/dist/mcp/grantAccess.d.ts +27 -0
  17. package/dist/mcp/grantAccess.js +29 -0
  18. package/dist/mcp/oauth.js +86 -5
  19. package/dist/mcp/oauthMetadata.d.ts +32 -1
  20. package/dist/mcp/oauthMetadata.js +53 -2
  21. package/dist/mcp/registry.d.ts +8 -1
  22. package/dist/mcp/server.js +6 -1
  23. package/dist/mcp/toolGenerator.d.ts +5 -1
  24. package/dist/mcp/toolGenerator.js +11 -0
  25. package/dist/mcp/types.d.ts +11 -0
  26. package/dist/modelRouterWrites.d.ts +23 -0
  27. package/dist/modelRouterWrites.js +54 -0
  28. package/dist/openApi.d.ts +7 -0
  29. package/dist/openApi.js +6 -6
  30. package/dist/permissions.js +5 -4
  31. package/dist/rbac/access.js +2 -0
  32. package/dist/rbac/routes.js +1 -0
  33. package/dist/rbac/statements.d.ts +12 -1
  34. package/dist/rbac/statements.js +89 -1
  35. package/dist/rbac/types.d.ts +9 -2
  36. package/dist/sync/executors.d.ts +6 -4
  37. package/dist/sync/executors.js +6 -2
  38. package/package.json +6 -6
  39. package/src/actions.ts +6 -0
  40. package/src/api.ts +95 -33
  41. package/src/bulk.test.ts +1256 -0
  42. package/src/bulk.ts +680 -0
  43. package/src/bulkOpenApi.test.ts +172 -0
  44. package/src/bulkOpenApi.ts +126 -0
  45. package/src/bulkTransaction.test.ts +197 -0
  46. package/src/bulkTransaction.ts +149 -0
  47. package/src/errors.ts +2 -2
  48. package/src/index.ts +6 -0
  49. package/src/isolated/bulkAtomic.isolated.ts +630 -0
  50. package/src/isolated/bulkStandalone.isolated.ts +133 -0
  51. package/src/isolated/mongoTopology.isolated.ts +29 -0
  52. package/src/mcp/actionTools.ts +2 -0
  53. package/src/mcp/grantAccess.test.ts +107 -0
  54. package/src/mcp/grantAccess.ts +49 -0
  55. package/src/mcp/oauth.test.ts +327 -0
  56. package/src/mcp/oauth.ts +113 -5
  57. package/src/mcp/oauthMetadata.test.ts +125 -1
  58. package/src/mcp/oauthMetadata.ts +99 -2
  59. package/src/mcp/registry.ts +8 -1
  60. package/src/mcp/server.test.ts +419 -2
  61. package/src/mcp/server.ts +8 -1
  62. package/src/mcp/toolGenerator.ts +17 -0
  63. package/src/mcp/types.ts +12 -0
  64. package/src/modelRouterWrites.ts +72 -0
  65. package/src/openApi.ts +1 -1
  66. package/src/permissions.ts +5 -5
  67. package/src/rbac/access.ts +3 -1
  68. package/src/rbac/routes.test.ts +15 -0
  69. package/src/rbac/routes.ts +1 -0
  70. package/src/rbac/statements.test.ts +23 -0
  71. package/src/rbac/statements.ts +100 -1
  72. package/src/rbac/types.ts +9 -2
  73. package/src/sync/executors.test.ts +27 -0
  74. package/src/sync/executors.ts +12 -4
  75. package/src/tests/mongoTopology.ts +53 -0
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Atomic `POST /<route>/bulk` on a Mongo without transaction support. Isolated because
3
+ * `useMongoTopology` swaps the default mongoose connection to an in-memory standalone server
4
+ * for this process.
5
+ */
6
+ import {afterEach, beforeEach, describe, expect, it} from "bun:test";
7
+ import {expectAPIError} from "@terreno/test";
8
+ import type express from "express";
9
+
10
+ import {modelRouter} from "../api";
11
+ import {addAuthRoutes, setupAuth, type UserModel as UserMongooseModel} from "../auth";
12
+ import {apiUnauthorizedMiddleware} from "../errors";
13
+ import {resetOpenApiValidatorConfig} from "../openApiValidator";
14
+ import {Permissions} from "../permissions";
15
+ import {authAsUser, type Food, FoodModel, getBaseServer, setupDb, UserModel} from "../tests";
16
+ import {useMongoTopology} from "../tests/mongoTopology";
17
+
18
+ useMongoTopology({topology: "standalone"});
19
+
20
+ const allPermissions = {
21
+ create: [Permissions.IsAuthenticated],
22
+ delete: [Permissions.IsAuthenticated],
23
+ list: [Permissions.IsAuthenticated],
24
+ read: [Permissions.IsAuthenticated],
25
+ update: [Permissions.IsAuthenticated],
26
+ };
27
+
28
+ type RouterOptions = Parameters<typeof modelRouter<Food>>[1];
29
+
30
+ const unsupportedDetail = /requires a replica set; send atomic:false for per-item writes/;
31
+
32
+ const bulkFoodNames = async (): Promise<string[]> => {
33
+ const docs = await FoodModel.find({name: /^bulk-/}).sort({name: 1});
34
+ return docs.map((doc) => doc.name as string);
35
+ };
36
+
37
+ describe("modelRouter bulk atomic mode (standalone Mongo)", () => {
38
+ let app: express.Application;
39
+
40
+ const mountFood = (options: Partial<RouterOptions> = {}): void => {
41
+ app.use(
42
+ "/food",
43
+ modelRouter(FoodModel, {
44
+ bulk: true,
45
+ permissions: allPermissions,
46
+ ...options,
47
+ } as RouterOptions)
48
+ );
49
+ app.use(apiUnauthorizedMiddleware);
50
+ // Terminal handler so an unmatched route answers 404 instead of hanging.
51
+ app.use((_req: express.Request, res: express.Response) => {
52
+ res.status(404).json({title: "Not Found"});
53
+ });
54
+ };
55
+
56
+ beforeEach(async () => {
57
+ process.env.REFRESH_TOKEN_SECRET = "testsecret1234";
58
+ await setupDb();
59
+ await FoodModel.deleteMany({});
60
+ app = getBaseServer();
61
+ setupAuth(app, UserModel as unknown as UserMongooseModel);
62
+ addAuthRoutes(app, UserModel as unknown as UserMongooseModel);
63
+ });
64
+
65
+ afterEach(() => {
66
+ resetOpenApiValidatorConfig();
67
+ });
68
+
69
+ it("returns 400 bulk-atomic-unsupported with nothing written, and atomic:false still works", async () => {
70
+ let preCreateCalls = 0;
71
+ mountFood({
72
+ preCreate: (body: Partial<Food>) => {
73
+ preCreateCalls += 1;
74
+ return body as Food;
75
+ },
76
+ } as Partial<RouterOptions>);
77
+ const agent = await authAsUser(app, "notAdmin");
78
+
79
+ const res = await agent.post("/food/bulk").send({
80
+ operations: [
81
+ {body: {name: "bulk-a"}, method: "create"},
82
+ {body: {name: "bulk-b"}, method: "create"},
83
+ ],
84
+ });
85
+
86
+ expectAPIError(res, {code: "bulk-atomic-unsupported", detail: unsupportedDetail, status: 400});
87
+ expect(await bulkFoodNames()).toEqual([]);
88
+ // Detected before any write, so no item's hook ran.
89
+ expect(preCreateCalls).toBe(0);
90
+
91
+ const partial = await agent
92
+ .post("/food/bulk")
93
+ .send({
94
+ atomic: false,
95
+ operations: [
96
+ {body: {name: "bulk-a"}, method: "create"},
97
+ {body: {name: "bulk-b"}, method: "create"},
98
+ ],
99
+ })
100
+ .expect(200);
101
+ expect(partial.body.data.map((entry: {status: number}) => entry.status)).toEqual([201, 201]);
102
+ expect(await bulkFoodNames()).toEqual(["bulk-a", "bulk-b"]);
103
+ });
104
+
105
+ it("returns 400 bulk-atomic-unsupported for an explicit atomic:true", async () => {
106
+ mountFood();
107
+ const agent = await authAsUser(app, "notAdmin");
108
+ const res = await agent.post("/food/bulk").send({
109
+ atomic: true,
110
+ operations: [{body: {name: "bulk-a"}, method: "create"}],
111
+ });
112
+ expectAPIError(res, {code: "bulk-atomic-unsupported", detail: unsupportedDetail, status: 400});
113
+ expect(await bulkFoodNames()).toEqual([]);
114
+ });
115
+
116
+ it("returns 400 bulk-atomic-unsupported without deleting or updating existing docs", async () => {
117
+ mountFood();
118
+ const agent = await authAsUser(app, "notAdmin");
119
+ const keep = await FoodModel.create({calories: 1, likesIds: [], name: "bulk-keep"} as never);
120
+ const edit = await FoodModel.create({calories: 1, likesIds: [], name: "bulk-edit"} as never);
121
+
122
+ const res = await agent.post("/food/bulk").send({
123
+ operations: [
124
+ {id: keep.id, method: "delete"},
125
+ {body: {calories: 9}, id: edit.id, method: "update"},
126
+ ],
127
+ });
128
+
129
+ expectAPIError(res, {code: "bulk-atomic-unsupported", status: 400});
130
+ expect(await bulkFoodNames()).toEqual(["bulk-edit", "bulk-keep"]);
131
+ expect((await FoodModel.findById(edit.id))?.calories).toBe(1);
132
+ });
133
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Isolated because `useMongoTopology` swaps the default mongoose connection to an in-memory
3
+ * replica set for this process.
4
+ */
5
+ import {describe, expect, it} from "bun:test";
6
+ import mongoose from "mongoose";
7
+
8
+ import {useMongoTopology} from "../tests/mongoTopology";
9
+
10
+ useMongoTopology({topology: "replicaSet"});
11
+
12
+ describe("useMongoTopology replicaSet", () => {
13
+ it("connects to a replica set that supports transactions", async () => {
14
+ const hello = await mongoose.connection.db?.admin().command({hello: 1});
15
+ expect(hello?.setName).toBeTruthy();
16
+
17
+ const collection = mongoose.connection.collection("topologycanaries");
18
+ const session = await mongoose.connection.startSession();
19
+ try {
20
+ session.startTransaction();
21
+ await collection.insertOne({name: "aborted"}, {session});
22
+ await session.abortTransaction();
23
+ } finally {
24
+ await session.endSession();
25
+ }
26
+
27
+ expect(await collection.countDocuments({name: "aborted"})).toBe(0);
28
+ });
29
+ });
@@ -199,6 +199,7 @@ export const generateActionTools = (records: CollectionRecord[]): MCPToolDefinit
199
199
  const toolName = entry.config.mcp?.name as string;
200
200
  const zodSchema = buildActionInputSchema(entry.scope, entry.config);
201
201
  tools.push({
202
+ access: entry.config.method === "GET" ? "read" : "write",
202
203
  description: describeAction(entry),
203
204
  handler: (args: MCPToolArgs, user?: User) =>
204
205
  executeTool({
@@ -212,6 +213,7 @@ export const generateActionTools = (records: CollectionRecord[]): MCPToolDefinit
212
213
  }),
213
214
  inputSchema: toJSONSchema(zodSchema) as MCPToolInputSchema,
214
215
  name: toolName,
216
+ scope: entry.config.mcp?.scope,
215
217
  zodSchema,
216
218
  });
217
219
  }
@@ -0,0 +1,107 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {canUseMcpTool} from "./grantAccess";
4
+ import {MCP_OAUTH_GRANT_PRESETS, type McpOAuthGrant} from "./oauthMetadata";
5
+ import type {MCPToolDefinition} from "./toolGenerator";
6
+
7
+ const readTool = {access: "read"} as unknown as MCPToolDefinition;
8
+ const writeTool = {access: "write"} as unknown as MCPToolDefinition;
9
+ const scopedWriteTool = {access: "write", scope: "todos:admin"} as unknown as MCPToolDefinition;
10
+ const scopedReadTool = {access: "read", scope: "todos:admin"} as unknown as MCPToolDefinition;
11
+
12
+ const readWrite: McpOAuthGrant[] = [...MCP_OAUTH_GRANT_PRESETS.readWrite];
13
+ const readOnly: McpOAuthGrant[] = [...MCP_OAUTH_GRANT_PRESETS.readOnly];
14
+ const custom: McpOAuthGrant[] = [
15
+ ...readWrite,
16
+ {access: "write", label: "Todo admin", scope: "todos:admin"},
17
+ {access: "read", label: "Todo viewer", scope: "todos:view"},
18
+ ];
19
+
20
+ const allowed = (
21
+ tool: MCPToolDefinition,
22
+ tokenScopes: string[],
23
+ grants: McpOAuthGrant[] | undefined = readWrite,
24
+ credential = "oauth"
25
+ ): boolean => canUseMcpTool({credential, grants, tokenScopes, tool} as never);
26
+
27
+ describe("canUseMcpTool", () => {
28
+ describe("credentials and apps outside grant enforcement", () => {
29
+ it.each(["jwt", "better-auth-session", "mcp-service-token"])(
30
+ "allows a %s credential every tool even with no scopes",
31
+ (credential) => {
32
+ expect(allowed(writeTool, [], readWrite, credential)).toBe(true);
33
+ expect(allowed(scopedWriteTool, [], readWrite, credential)).toBe(true);
34
+ }
35
+ );
36
+
37
+ it("allows an oauth token every tool when grants is undefined", () => {
38
+ // Call directly: passing undefined to allowed() would apply its readWrite default
39
+ const call = (tool: MCPToolDefinition, tokenScopes: string[]): boolean =>
40
+ canUseMcpTool({credential: "oauth", grants: undefined, tokenScopes, tool});
41
+ expect(call(writeTool, ["mcp"])).toBe(true);
42
+ expect(call(scopedWriteTool, [])).toBe(true);
43
+ });
44
+ });
45
+
46
+ describe("untagged tools", () => {
47
+ it("lets mcp:read use a read tool but not a write tool", () => {
48
+ expect(allowed(readTool, ["mcp:read"])).toBe(true);
49
+ expect(allowed(writeTool, ["mcp:read"])).toBe(false);
50
+ });
51
+
52
+ it("lets mcp:write use read and write tools (write implies read)", () => {
53
+ expect(allowed(readTool, ["mcp:write"])).toBe(true);
54
+ expect(allowed(writeTool, ["mcp:write"])).toBe(true);
55
+ });
56
+
57
+ it("lets mcp:read mcp:write use a write tool", () => {
58
+ expect(allowed(writeTool, ["mcp:read", "mcp:write"])).toBe(true);
59
+ });
60
+
61
+ it("allows nothing for a token with no scopes", () => {
62
+ expect(allowed(readTool, [])).toBe(false);
63
+ expect(allowed(writeTool, [])).toBe(false);
64
+ });
65
+
66
+ it("allows nothing for a legacy mcp scope that maps to no grant", () => {
67
+ expect(allowed(readTool, ["mcp"])).toBe(false);
68
+ expect(allowed(writeTool, ["mcp"])).toBe(false);
69
+ });
70
+
71
+ it("ignores a scope the grants do not define", () => {
72
+ expect(allowed(readTool, ["unknown"])).toBe(false);
73
+ expect(allowed(readTool, ["unknown", "mcp:read"])).toBe(true);
74
+ });
75
+
76
+ it("does not let a token claim write under a readOnly preset", () => {
77
+ expect(allowed(writeTool, ["mcp:write"], readOnly)).toBe(false);
78
+ expect(allowed(readTool, ["mcp:read"], readOnly)).toBe(true);
79
+ });
80
+
81
+ it("applies a custom write grant's access level to untagged tools", () => {
82
+ expect(allowed(writeTool, ["todos:admin"], custom)).toBe(true);
83
+ expect(allowed(readTool, ["todos:admin"], custom)).toBe(true);
84
+ });
85
+
86
+ it("applies a custom read grant's access level to untagged tools", () => {
87
+ expect(allowed(readTool, ["todos:view"], custom)).toBe(true);
88
+ expect(allowed(writeTool, ["todos:view"], custom)).toBe(false);
89
+ });
90
+ });
91
+
92
+ describe("tools that declare a scope", () => {
93
+ it("requires exactly that scope", () => {
94
+ expect(allowed(scopedWriteTool, ["todos:admin"], custom)).toBe(true);
95
+ expect(allowed(scopedReadTool, ["todos:admin"], custom)).toBe(true);
96
+ });
97
+
98
+ it("refuses a token that only has a broader access grant", () => {
99
+ expect(allowed(scopedWriteTool, ["mcp:read", "mcp:write"], custom)).toBe(false);
100
+ expect(allowed(scopedReadTool, ["mcp:read", "mcp:write"], custom)).toBe(false);
101
+ });
102
+
103
+ it("refuses a token with no scopes", () => {
104
+ expect(allowed(scopedReadTool, [], custom)).toBe(false);
105
+ });
106
+ });
107
+ });
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Grant enforcement for MCP OAuth tokens: decides which tools a token may see and call from the
3
+ * scopes it was granted and the app's resolved `mcpOAuth.grants`.
4
+ */
5
+ import type {RequestCredential} from "../requestContext";
6
+ import type {McpOAuthGrant} from "./oauthMetadata";
7
+ import type {MCPToolDefinition} from "./toolGenerator";
8
+
9
+ export interface CanUseMcpToolOptions {
10
+ /** The tool being listed or called. Only its `access` and `scope` are read. */
11
+ tool: Pick<MCPToolDefinition, "access" | "scope">;
12
+ /** How the caller authenticated. Only `oauth` credentials are limited by grants. */
13
+ credential: RequestCredential | undefined;
14
+ /** Scopes on the caller's OAuth access token. */
15
+ tokenScopes: string[] | undefined;
16
+ /** Resolved `mcpOAuth.grants`, or undefined when the app does not enforce grants. */
17
+ grants: McpOAuthGrant[] | undefined;
18
+ }
19
+
20
+ /**
21
+ * True when the caller may see and call `tool`.
22
+ *
23
+ * - Credentials other than an OAuth token, and apps without `grants`, may use every tool.
24
+ * - A tool that declares `scope` requires exactly that scope on the token.
25
+ * - A `read` tool needs a granted scope whose grant has `read` or `write` access (write implies
26
+ * read); a `write` tool needs a granted scope whose grant has `write` access.
27
+ * - Token scopes that match no grant (for example the legacy `mcp` scope) allow nothing.
28
+ */
29
+ export const canUseMcpTool = ({
30
+ tool,
31
+ credential,
32
+ tokenScopes,
33
+ grants,
34
+ }: CanUseMcpToolOptions): boolean => {
35
+ if (credential !== "oauth" || !grants) {
36
+ return true;
37
+ }
38
+ const scopes = tokenScopes ?? [];
39
+ if (tool.scope) {
40
+ return scopes.includes(tool.scope);
41
+ }
42
+ const grantedAccess = grants
43
+ .filter((grant) => scopes.includes(grant.scope))
44
+ .map((grant) => grant.access);
45
+ if (tool.access === "read") {
46
+ return grantedAccess.length > 0;
47
+ }
48
+ return grantedAccess.includes("write");
49
+ };
@@ -282,6 +282,62 @@ describe("MCP OAuth authorization server", () => {
282
282
  });
283
283
 
284
284
  describe("authorization code flow", () => {
285
+ describe("under mcpOAuth.grants: readOnly", () => {
286
+ const authorizeWithScope = async (
287
+ scope: string,
288
+ grants: McpOAuthOptions["grants"] = "readOnly"
289
+ ): Promise<supertest.Response> => {
290
+ const readOnlyApp = buildApp({
291
+ mcpOAuth: {...oauthOptions, grants},
292
+ });
293
+ const clientId = await registerClient(readOnlyApp);
294
+ return startAuthorization(readOnlyApp, {
295
+ client_id: clientId,
296
+ code_challenge: createPkce().challenge,
297
+ code_challenge_method: "S256",
298
+ redirect_uri: REDIRECT_URI,
299
+ resource: `${ISSUER}/mcp`,
300
+ response_type: "code",
301
+ scope,
302
+ state: "state-ro",
303
+ });
304
+ };
305
+
306
+ it("redirects scope=mcp:write with error=invalid_scope", async () => {
307
+ const res = await authorizeWithScope("mcp:write");
308
+
309
+ expect(res.status).toBe(302);
310
+ const redirect = new URL(res.headers.location);
311
+ expect(`${redirect.origin}${redirect.pathname}`).toBe(REDIRECT_URI);
312
+ expect(redirect.searchParams.get("error")).toBe("invalid_scope");
313
+ expect(redirect.searchParams.get("state")).toBe("state-ro");
314
+ });
315
+
316
+ it("redirects the legacy scope=mcp with error=invalid_scope", async () => {
317
+ const res = await authorizeWithScope("mcp");
318
+
319
+ expect(new URL(res.headers.location).searchParams.get("error")).toBe("invalid_scope");
320
+ });
321
+
322
+ it("accepts scope=mcp:write under readWrite", async () => {
323
+ const res = await authorizeWithScope("mcp:write", "readWrite");
324
+
325
+ const redirect = new URL(res.headers.location);
326
+ expect(redirect.origin).toBe("https://app.example.com");
327
+ expect(redirect.searchParams.get("error")).toBeNull();
328
+ });
329
+
330
+ it("accepts scope=mcp:read and goes on to the consent page", async () => {
331
+ const res = await authorizeWithScope("mcp:read");
332
+
333
+ expect(res.status).toBe(302);
334
+ const redirect = new URL(res.headers.location);
335
+ expect(redirect.origin).toBe("https://app.example.com");
336
+ expect(redirect.searchParams.get("error")).toBeNull();
337
+ expect(redirect.searchParams.get("request")).toBeTruthy();
338
+ });
339
+ });
340
+
285
341
  it("issues access and refresh tokens that call /mcp as the approving user", async () => {
286
342
  const clientId = await registerClient(app);
287
343
  const {challenge, verifier} = createPkce();
@@ -994,6 +1050,277 @@ describe("MCP OAuth authorization server", () => {
994
1050
  "approveMcpOAuthRequest"
995
1051
  );
996
1052
  });
1053
+ describe("consent scope narrowing and grant metadata", () => {
1054
+ const rwOptions: McpOAuthOptions = {...oauthOptions, grants: "readWrite"};
1055
+
1056
+ interface Pending {
1057
+ clientId: string;
1058
+ requestId: string;
1059
+ rwApp: express.Application;
1060
+ rwAgent: TestAgent;
1061
+ verifier: string;
1062
+ }
1063
+
1064
+ const startPending = async (
1065
+ scope: string | undefined,
1066
+ mcpOAuth: McpOAuthOptions = rwOptions
1067
+ ): Promise<Pending> => {
1068
+ const rwApp = buildApp({mcpOAuth});
1069
+ const rwAgent = await authAsUser(rwApp, "notAdmin");
1070
+ const clientId = await registerClient(rwApp);
1071
+ const {challenge, verifier} = createPkce();
1072
+ const params: Record<string, string> = {
1073
+ client_id: clientId,
1074
+ code_challenge: challenge,
1075
+ code_challenge_method: "S256",
1076
+ redirect_uri: REDIRECT_URI,
1077
+ response_type: "code",
1078
+ state: "state-t3",
1079
+ };
1080
+ if (scope !== undefined) {
1081
+ params.scope = scope;
1082
+ }
1083
+ const authorize = await startAuthorization(rwApp, params);
1084
+ expect(authorize.status).toBe(302);
1085
+ return {
1086
+ clientId,
1087
+ requestId: requestIdFrom(authorize.headers.location),
1088
+ rwAgent,
1089
+ rwApp,
1090
+ verifier,
1091
+ };
1092
+ };
1093
+
1094
+ const approveAndExchange = async (
1095
+ pending: Pending,
1096
+ body?: Record<string, unknown>
1097
+ ): Promise<supertest.Response> => {
1098
+ const approve =
1099
+ body === undefined
1100
+ ? await pending.rwAgent.post(`/oauth/authorize/${pending.requestId}/approve`)
1101
+ : await pending.rwAgent.post(`/oauth/authorize/${pending.requestId}/approve`).send(body);
1102
+ expect(approve.status).toBe(200);
1103
+ const code = new URL(approve.body.data.redirectUrl).searchParams.get("code") as string;
1104
+ return exchangeCode(pending.rwApp, {
1105
+ clientId: pending.clientId,
1106
+ code,
1107
+ verifier: pending.verifier,
1108
+ });
1109
+ };
1110
+
1111
+ it("GET lists each requested grant with its preset label, in requested order", async () => {
1112
+ const pending = await startPending("mcp:read mcp:write");
1113
+
1114
+ const res = await pending.rwAgent.get(`/oauth/authorize/${pending.requestId}`);
1115
+
1116
+ expect(res.status).toBe(200);
1117
+ expect(res.body.data.grants).toEqual([
1118
+ {
1119
+ access: "read",
1120
+ description: "See your records. It cannot change anything.",
1121
+ label: "Read your data",
1122
+ scope: "mcp:read",
1123
+ },
1124
+ {
1125
+ access: "write",
1126
+ description: "Create, update, and delete records for you.",
1127
+ label: "Change your data",
1128
+ scope: "mcp:write",
1129
+ },
1130
+ ]);
1131
+ });
1132
+
1133
+ it("GET keeps the requested order when the client asks for write first", async () => {
1134
+ const pending = await startPending("mcp:write mcp:read");
1135
+
1136
+ const res = await pending.rwAgent.get(`/oauth/authorize/${pending.requestId}`);
1137
+
1138
+ expect(res.body.data.grants.map((grant: {scope: string}) => grant.scope)).toEqual([
1139
+ "mcp:write",
1140
+ "mcp:read",
1141
+ ]);
1142
+ });
1143
+
1144
+ it("GET lists only the requested subset of the grants", async () => {
1145
+ const pending = await startPending("mcp:read");
1146
+
1147
+ const res = await pending.rwAgent.get(`/oauth/authorize/${pending.requestId}`);
1148
+
1149
+ expect(res.body.data.grants).toHaveLength(1);
1150
+ expect(res.body.data.grants[0]).toMatchObject({label: "Read your data", scope: "mcp:read"});
1151
+ });
1152
+
1153
+ it("GET synthesizes a write grant per scope when grants is unset", async () => {
1154
+ const pending = await startPending("mcp", oauthOptions);
1155
+
1156
+ const res = await pending.rwAgent.get(`/oauth/authorize/${pending.requestId}`);
1157
+
1158
+ expect(res.body.data.grants).toEqual([
1159
+ {access: "write", description: null, label: "mcp", scope: "mcp"},
1160
+ ]);
1161
+ });
1162
+
1163
+ it("approve {scope: mcp:read} issues a token and a refresh with scope mcp:read", async () => {
1164
+ const pending = await startPending("mcp:read mcp:write");
1165
+
1166
+ const token = await approveAndExchange(pending, {scope: "mcp:read"});
1167
+
1168
+ expect(token.status).toBe(200);
1169
+ expect(token.body.scope).toBe("mcp:read");
1170
+ const refreshed = await refresh(pending.rwApp, pending.clientId, token.body.refresh_token);
1171
+ expect(refreshed.status).toBe(200);
1172
+ expect(refreshed.body.scope).toBe("mcp:read");
1173
+ const second = await refresh(pending.rwApp, pending.clientId, refreshed.body.refresh_token);
1174
+ expect(second.body.scope).toBe("mcp:read");
1175
+ });
1176
+
1177
+ it("approve with no body grants the full requested scope", async () => {
1178
+ const pending = await startPending("mcp:read mcp:write");
1179
+
1180
+ const token = await approveAndExchange(pending);
1181
+
1182
+ expect(token.status).toBe(200);
1183
+ expect(token.body.scope).toBe("mcp:read mcp:write");
1184
+ });
1185
+
1186
+ it("approve with an empty JSON object grants the full requested scope", async () => {
1187
+ const pending = await startPending("mcp:read mcp:write");
1188
+
1189
+ const token = await approveAndExchange(pending, {});
1190
+
1191
+ expect(token.body.scope).toBe("mcp:read mcp:write");
1192
+ });
1193
+
1194
+ it("approve {scope: ''} is a 400 and leaves the request pending", async () => {
1195
+ const pending = await startPending("mcp:read mcp:write");
1196
+
1197
+ const empty = await pending.rwAgent
1198
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1199
+ .send({scope: ""});
1200
+ const whitespace = await pending.rwAgent
1201
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1202
+ .send({scope: " "});
1203
+
1204
+ expect(empty.status).toBe(400);
1205
+ expect(empty.body.title).toBe("Choose at least one permission");
1206
+ expect(whitespace.status).toBe(400);
1207
+ expect(whitespace.body.title).toBe("Choose at least one permission");
1208
+ const token = await approveAndExchange(pending, {scope: "mcp:read"});
1209
+ expect(token.body.scope).toBe("mcp:read");
1210
+ });
1211
+
1212
+ it("approve {scope: 'mcp:write admin'} is a 400 Scope was not requested", async () => {
1213
+ const pending = await startPending("mcp:read mcp:write");
1214
+
1215
+ const res = await pending.rwAgent
1216
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1217
+ .send({scope: "mcp:write admin"});
1218
+
1219
+ expect(res.status).toBe(400);
1220
+ expect(res.body.title).toBe("Scope was not requested");
1221
+ });
1222
+
1223
+ it("never widens: approving mcp:write on a read-only request is a 400", async () => {
1224
+ const pending = await startPending("mcp:read");
1225
+
1226
+ const res = await pending.rwAgent
1227
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1228
+ .send({scope: "mcp:write"});
1229
+
1230
+ expect(res.status).toBe(400);
1231
+ expect(await McpOAuthToken.countDocuments({})).toBe(0);
1232
+ });
1233
+
1234
+ it("a rejected narrowing leaves the request pending for a valid approve", async () => {
1235
+ const pending = await startPending("mcp:read");
1236
+
1237
+ await pending.rwAgent
1238
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1239
+ .send({scope: "mcp:write"});
1240
+ const token = await approveAndExchange(pending, {scope: "mcp:read"});
1241
+
1242
+ expect(token.body.scope).toBe("mcp:read");
1243
+ });
1244
+
1245
+ it("approve without a session is 401", async () => {
1246
+ const pending = await startPending("mcp:read mcp:write");
1247
+
1248
+ const res = await supertest(pending.rwApp)
1249
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1250
+ .send({scope: "mcp:read"});
1251
+
1252
+ expect(res.status).toBe(401);
1253
+ });
1254
+
1255
+ it("approve twice with a narrowed scope is 409 on the second call", async () => {
1256
+ const pending = await startPending("mcp:read mcp:write");
1257
+
1258
+ await approveAndExchange(pending, {scope: "mcp:read"});
1259
+ const again = await pending.rwAgent
1260
+ .post(`/oauth/authorize/${pending.requestId}/approve`)
1261
+ .send({scope: "mcp:read"});
1262
+
1263
+ expect(again.status).toBe(409);
1264
+ });
1265
+
1266
+ it("client_credentials under readWrite with no stored scope gets mcp:read mcp:write", async () => {
1267
+ const rwApp = buildApp({mcpOAuth: rwOptions});
1268
+ const created = await McpOAuthClient.issueConfidential({
1269
+ clientName: "Sandbox agent",
1270
+ tokenEndpointAuthMethod: "client_secret_post",
1271
+ userId: notAdminId,
1272
+ });
1273
+
1274
+ const token = await supertest(rwApp).post("/oauth/token").type("form").send({
1275
+ client_id: created.client.clientId,
1276
+ client_secret: created.clientSecret,
1277
+ grant_type: "client_credentials",
1278
+ });
1279
+
1280
+ expect(token.status).toBe(200);
1281
+ expect(token.body.scope).toBe("mcp:read mcp:write");
1282
+ });
1283
+
1284
+ it("client_credentials under readWrite with stored scope mcp is invalid_scope", async () => {
1285
+ const rwApp = buildApp({mcpOAuth: rwOptions});
1286
+ const created = await McpOAuthClient.issueConfidential({
1287
+ clientName: "Legacy agent",
1288
+ scope: "mcp",
1289
+ tokenEndpointAuthMethod: "client_secret_post",
1290
+ userId: notAdminId,
1291
+ });
1292
+
1293
+ const token = await supertest(rwApp).post("/oauth/token").type("form").send({
1294
+ client_id: created.client.clientId,
1295
+ client_secret: created.clientSecret,
1296
+ grant_type: "client_credentials",
1297
+ });
1298
+
1299
+ expect(token.status).toBe(400);
1300
+ expect(token.body.error).toBe("invalid_scope");
1301
+ expect(await McpOAuthToken.countDocuments({})).toBe(0);
1302
+ });
1303
+
1304
+ it("client_credentials under readWrite with stored scope mcp:read gets mcp:read", async () => {
1305
+ const rwApp = buildApp({mcpOAuth: rwOptions});
1306
+ const created = await McpOAuthClient.issueConfidential({
1307
+ clientName: "Reader",
1308
+ scope: "mcp:read",
1309
+ tokenEndpointAuthMethod: "client_secret_post",
1310
+ userId: notAdminId,
1311
+ });
1312
+
1313
+ const token = await supertest(rwApp).post("/oauth/token").type("form").send({
1314
+ client_id: created.client.clientId,
1315
+ client_secret: created.clientSecret,
1316
+ grant_type: "client_credentials",
1317
+ });
1318
+
1319
+ expect(token.status).toBe(200);
1320
+ expect(token.body.scope).toBe("mcp:read");
1321
+ });
1322
+ });
1323
+
997
1324
  describe("client credentials", () => {
998
1325
  const basicAuthorization = (clientId: string, clientSecret: string): string => {
999
1326
  const encoded = Buffer.from(