@terreno/api 57.0.0 → 57.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 (175) hide show
  1. package/.ai/skills/mongoose-schema-safety/SKILL.md +8 -0
  2. package/dist/actions.d.ts +7 -2
  3. package/dist/actions.js +60 -25
  4. package/dist/adminModelRouter.d.ts +14 -0
  5. package/dist/adminModelRouter.js +199 -0
  6. package/dist/adminTypes.d.ts +156 -0
  7. package/dist/adminTypes.js +5 -0
  8. package/dist/api.d.ts +44 -3
  9. package/dist/api.js +74 -26
  10. package/dist/auth.d.ts +18 -1
  11. package/dist/auth.js +122 -20
  12. package/dist/consentApp.d.ts +2 -0
  13. package/dist/consentApp.js +98 -0
  14. package/dist/index.d.ts +22 -1
  15. package/dist/index.js +51 -7
  16. package/dist/mcp/auth.d.ts +11 -0
  17. package/dist/mcp/auth.js +133 -0
  18. package/dist/mcp/createMCPRequest.d.ts +16 -0
  19. package/dist/mcp/createMCPRequest.js +26 -0
  20. package/dist/mcp/handlers.d.ts +8 -0
  21. package/dist/mcp/handlers.js +793 -0
  22. package/dist/mcp/query.d.ts +32 -0
  23. package/dist/mcp/query.js +232 -0
  24. package/dist/mcp/registry.d.ts +21 -0
  25. package/dist/mcp/registry.js +54 -0
  26. package/dist/mcp/schemaGenerator.d.ts +14 -0
  27. package/dist/mcp/schemaGenerator.js +379 -0
  28. package/dist/mcp/server.d.ts +8 -0
  29. package/dist/mcp/server.js +133 -0
  30. package/dist/mcp/toolGenerator.d.ts +14 -0
  31. package/dist/mcp/toolGenerator.js +246 -0
  32. package/dist/mcp/types.d.ts +85 -0
  33. package/dist/mcp/types.js +2 -0
  34. package/dist/openApi.d.ts +1 -1
  35. package/dist/openApi.js +26 -8
  36. package/dist/permissions.js +15 -15
  37. package/dist/rbac/access.d.ts +3 -0
  38. package/dist/rbac/access.js +294 -0
  39. package/dist/rbac/auditModel.d.ts +31 -0
  40. package/dist/rbac/auditModel.js +112 -0
  41. package/dist/rbac/backfillAdmins.d.ts +18 -0
  42. package/dist/rbac/backfillAdmins.js +139 -0
  43. package/dist/rbac/fieldViews.d.ts +3 -0
  44. package/dist/rbac/fieldViews.js +201 -0
  45. package/dist/rbac/middleware.d.ts +21 -0
  46. package/dist/rbac/middleware.js +108 -0
  47. package/dist/rbac/modelRouterAccess.d.ts +42 -0
  48. package/dist/rbac/modelRouterAccess.js +388 -0
  49. package/dist/rbac/permissionUtils.d.ts +8 -0
  50. package/dist/rbac/permissionUtils.js +209 -0
  51. package/dist/rbac/realtimeAccess.d.ts +18 -0
  52. package/dist/rbac/realtimeAccess.js +173 -0
  53. package/dist/rbac/resolve.d.ts +28 -0
  54. package/dist/rbac/resolve.js +387 -0
  55. package/dist/rbac/roleManager.d.ts +20 -0
  56. package/dist/rbac/roleManager.js +741 -0
  57. package/dist/rbac/roleModel.d.ts +42 -0
  58. package/dist/rbac/roleModel.js +267 -0
  59. package/dist/rbac/routes.d.ts +9 -0
  60. package/dist/rbac/routes.js +211 -0
  61. package/dist/rbac/scopes.d.ts +15 -0
  62. package/dist/rbac/scopes.js +155 -0
  63. package/dist/rbac/statements.d.ts +20 -0
  64. package/dist/rbac/statements.js +115 -0
  65. package/dist/rbac/types.d.ts +202 -0
  66. package/dist/rbac/types.js +2 -0
  67. package/dist/rbac/userPlugin.d.ts +12 -0
  68. package/dist/rbac/userPlugin.js +41 -0
  69. package/dist/realtime/changeStreamWatcher.d.ts +1 -1
  70. package/dist/realtime/changeStreamWatcher.js +48 -39
  71. package/dist/realtime/realtimeApp.js +4 -8
  72. package/dist/realtime/registry.d.ts +5 -0
  73. package/dist/realtime/registry.js +13 -1
  74. package/dist/scrubAdminFields.d.ts +17 -0
  75. package/dist/scrubAdminFields.js +192 -0
  76. package/dist/sync/executors.d.ts +1 -1
  77. package/dist/sync/executors.js +63 -40
  78. package/dist/sync/loadHarness.js +4 -5
  79. package/dist/sync/registry.d.ts +5 -0
  80. package/dist/sync/registry.js +13 -1
  81. package/dist/sync/routes.js +41 -36
  82. package/dist/sync/serialize.js +5 -6
  83. package/dist/terrenoApp.d.ts +18 -0
  84. package/dist/terrenoApp.js +46 -3
  85. package/dist/terrenoPlugin.d.ts +8 -1
  86. package/dist/tests/createTestData.js +8 -0
  87. package/dist/tests/models.d.ts +1 -0
  88. package/dist/tests/models.js +5 -0
  89. package/dist/tests/testHelper.js +1 -2
  90. package/dist/transformers.js +16 -1
  91. package/package.json +16 -12
  92. package/src/__snapshots__/openApi.test.ts.snap +192 -0
  93. package/src/actions.test.ts +194 -1
  94. package/src/actions.ts +65 -8
  95. package/src/adminModelRouter.ts +154 -0
  96. package/src/adminTypes.ts +183 -0
  97. package/src/api.test.ts +66 -1
  98. package/src/api.ts +131 -12
  99. package/src/auth.test.ts +135 -1
  100. package/src/auth.ts +81 -3
  101. package/src/consentApp.test.ts +24 -0
  102. package/src/consentApp.ts +100 -0
  103. package/src/index.ts +56 -0
  104. package/src/mcp/auth.test.ts +197 -0
  105. package/src/mcp/auth.ts +100 -0
  106. package/src/mcp/createMCPRequest.test.ts +47 -0
  107. package/src/mcp/createMCPRequest.ts +32 -0
  108. package/src/mcp/customTools.test.ts +54 -0
  109. package/src/mcp/handlers.ts +639 -0
  110. package/src/mcp/integration.test.ts +1493 -0
  111. package/src/mcp/query.test.ts +172 -0
  112. package/src/mcp/query.ts +179 -0
  113. package/src/mcp/registry.ts +70 -0
  114. package/src/mcp/schemaGenerator.test.ts +182 -0
  115. package/src/mcp/schemaGenerator.ts +354 -0
  116. package/src/mcp/server.test.ts +226 -0
  117. package/src/mcp/server.ts +86 -0
  118. package/src/mcp/toolGenerator.test.ts +284 -0
  119. package/src/mcp/toolGenerator.ts +199 -0
  120. package/src/mcp/types.ts +95 -0
  121. package/src/openApi.test.ts +107 -0
  122. package/src/openApi.ts +32 -1
  123. package/src/permissions.ts +3 -2
  124. package/src/rbac/access.test.ts +357 -0
  125. package/src/rbac/access.ts +201 -0
  126. package/src/rbac/auditModel.ts +103 -0
  127. package/src/rbac/backfillAdmins.ts +54 -0
  128. package/src/rbac/fieldViews.test.ts +39 -0
  129. package/src/rbac/fieldViews.ts +122 -0
  130. package/src/rbac/middleware.ts +55 -0
  131. package/src/rbac/modelRouterAccess.test.ts +336 -0
  132. package/src/rbac/modelRouterAccess.ts +331 -0
  133. package/src/rbac/permissionUtils.test.ts +112 -0
  134. package/src/rbac/permissionUtils.ts +83 -0
  135. package/src/rbac/realtimeAccess.test.ts +242 -0
  136. package/src/rbac/realtimeAccess.ts +138 -0
  137. package/src/rbac/resolve.test.ts +358 -0
  138. package/src/rbac/resolve.ts +285 -0
  139. package/src/rbac/roleManager.test.ts +915 -0
  140. package/src/rbac/roleManager.ts +440 -0
  141. package/src/rbac/roleModel.test.ts +114 -0
  142. package/src/rbac/roleModel.ts +196 -0
  143. package/src/rbac/routes.ts +170 -0
  144. package/src/rbac/scopes.test.ts +105 -0
  145. package/src/rbac/scopes.ts +81 -0
  146. package/src/rbac/statements.test.ts +65 -0
  147. package/src/rbac/statements.ts +62 -0
  148. package/src/rbac/types.ts +198 -0
  149. package/src/rbac/userPlugin.test.ts +55 -0
  150. package/src/rbac/userPlugin.ts +25 -0
  151. package/src/realtime/changeStreamWatcher.ts +20 -15
  152. package/src/realtime/realtime.test.ts +25 -1
  153. package/src/realtime/realtimeApp.ts +2 -5
  154. package/src/realtime/registry.ts +15 -0
  155. package/src/scrubAdminFields.test.ts +113 -0
  156. package/src/scrubAdminFields.ts +158 -0
  157. package/src/sync/executors.ts +31 -1
  158. package/src/sync/loadHarness.ts +8 -7
  159. package/src/sync/models.test.ts +262 -0
  160. package/src/sync/registry.ts +15 -0
  161. package/src/sync/routes.ts +25 -11
  162. package/src/sync/scripts/compactTombstones.test.ts +4 -6
  163. package/src/sync/serialize.ts +17 -9
  164. package/src/sync/sync.test.ts +52 -0
  165. package/src/sync/syncRoutes.test.ts +5 -2
  166. package/src/sync/syncSocket.test.ts +28 -0
  167. package/src/terrenoApp.test.ts +100 -0
  168. package/src/terrenoApp.ts +65 -3
  169. package/src/terrenoPlugin.ts +10 -1
  170. package/src/tests/bunSetup.ts +2 -0
  171. package/src/tests/createTestData.ts +5 -1
  172. package/src/tests/models.ts +6 -0
  173. package/src/tests/testHelper.ts +1 -3
  174. package/src/transformers.test.ts +12 -0
  175. package/src/transformers.ts +7 -1
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from "./actions";
2
+ export * from "./adminTypes";
2
3
  export * from "./api";
3
4
  export * from "./auth";
4
5
  export * from "./betterAuth";
@@ -14,6 +15,31 @@ export * from "./expressServer";
14
15
  export * from "./githubAuth";
15
16
  export * from "./httpClient";
16
17
  export * from "./logger";
18
+ export {extractUserFromHeaders, type MCPAuthContext} from "./mcp/auth";
19
+ export type {MCPCustomTool} from "./mcp/registry";
20
+ export {
21
+ clearMCPRegistry,
22
+ getMCPRegistry,
23
+ registerMCPModel,
24
+ registerMCPTool,
25
+ updateMCPRegistryOptions,
26
+ } from "./mcp/registry";
27
+ export {generateInputSchema, generateToolDescription} from "./mcp/schemaGenerator";
28
+ export {type MCPServerOptions, mountMCPServer} from "./mcp/server";
29
+ export {
30
+ generateAllTools,
31
+ generateToolsForEntry,
32
+ getAllMCPTools,
33
+ type MCPToolDefinition,
34
+ } from "./mcp/toolGenerator";
35
+ export type {
36
+ MCPConfig,
37
+ MCPMethod,
38
+ MCPRegistryEntry,
39
+ MCPRequest,
40
+ MCPToolArgs,
41
+ MCPToolResult,
42
+ } from "./mcp/types";
17
43
  export * from "./middleware";
18
44
  export * from "./models/consentForm";
19
45
  export * from "./models/consentResponse";
@@ -28,6 +54,34 @@ export * from "./openApiValidator";
28
54
  export * from "./permissions";
29
55
  export * from "./plugins";
30
56
  export * from "./populate";
57
+ export * from "./rbac/access";
58
+ export {
59
+ createRbacAuditModel,
60
+ type RbacAuditDocument,
61
+ recordRbacAudit,
62
+ } from "./rbac/auditModel";
63
+ export {
64
+ type BackfillAdminsOptions,
65
+ type BackfillAdminsResult,
66
+ backfillAdmins,
67
+ } from "./rbac/backfillAdmins";
68
+ export * from "./rbac/fieldViews";
69
+ export * from "./rbac/middleware";
70
+ export * from "./rbac/permissionUtils";
71
+ export {
72
+ createRbacRoleModel,
73
+ expandRolePermissions,
74
+ type RbacRoleDocument,
75
+ type RbacRoleModel,
76
+ READ_ONLY_ROLE_PERMISSIONS,
77
+ type RoleDefinition,
78
+ terrenoDefaultRoles,
79
+ } from "./rbac/roleModel";
80
+ export {type RbacRouterOptions, rbacRouter} from "./rbac/routes";
81
+ export * from "./rbac/scopes";
82
+ export * from "./rbac/statements";
83
+ export * from "./rbac/types";
84
+ export * from "./rbac/userPlugin";
31
85
  export {
32
86
  type AuthorizedEmitEntry,
33
87
  emitPayloadToAuthorizedRoom,
@@ -59,6 +113,7 @@ export {
59
113
  getRealtimeRegistry,
60
114
  type RealtimeRegistryEntry,
61
115
  registerRealtime,
116
+ updateRealtimeRegistryOptions,
62
117
  } from "./realtime/registry";
63
118
  export {
64
119
  DEFAULT_SESSION_REVALIDATION_INTERVAL_MS,
@@ -96,6 +151,7 @@ export type {
96
151
  } from "./realtime/types";
97
152
  export * from "./requestContext";
98
153
  export * from "./scriptRunner";
154
+ export {adminBodyFieldsToStrip, scrubAdminFields, stripAdminBodyFields} from "./scrubAdminFields";
99
155
  export * from "./secretProviders";
100
156
  export * from "./sync/executors";
101
157
  export * from "./sync/models";
@@ -0,0 +1,197 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import jwt from "jsonwebtoken";
3
+ import mongoose, {Schema} from "mongoose";
4
+
5
+ import type {UserModel} from "../auth";
6
+ import type {BetterAuthInstance} from "../betterAuthSetup";
7
+ import {findOneOrNone} from "../plugins";
8
+ import {extractUserFromHeaders} from "./auth";
9
+
10
+ interface MCPAuthUserFields {
11
+ _id: mongoose.Types.ObjectId;
12
+ betterAuthId?: string;
13
+ disabled?: boolean;
14
+ email?: string;
15
+ }
16
+
17
+ const userSchema = new Schema({
18
+ betterAuthId: {description: "Better Auth user id", index: true, type: String},
19
+ disabled: {default: false, description: "Whether the account is disabled", type: Boolean},
20
+ email: {description: "User email", type: String},
21
+ });
22
+ userSchema.plugin(findOneOrNone);
23
+
24
+ const getUserModel = (): mongoose.Model<MCPAuthUserFields> => {
25
+ try {
26
+ return mongoose.model<MCPAuthUserFields>("MCPAuthUser");
27
+ } catch {
28
+ return mongoose.model<MCPAuthUserFields>("MCPAuthUser", userSchema);
29
+ }
30
+ };
31
+
32
+ const UserTestModel = getUserModel();
33
+ const userModel = UserTestModel as unknown as UserModel;
34
+
35
+ /** Minimal Better Auth stand-in: only getSession is used by extractUserFromHeaders. */
36
+ const fakeBetterAuth = (
37
+ getSession: () => Promise<{session?: unknown; user?: {id: string}} | null>
38
+ ): BetterAuthInstance => {
39
+ return {api: {getSession}} as unknown as BetterAuthInstance;
40
+ };
41
+
42
+ const signToken = (payload: Record<string, unknown>, secret = "test-token-secret"): string => {
43
+ return jwt.sign(payload, secret, {issuer: process.env.TOKEN_ISSUER});
44
+ };
45
+
46
+ describe("extractUserFromHeaders", () => {
47
+ beforeEach(async () => {
48
+ await UserTestModel.deleteMany({});
49
+ process.env.TOKEN_SECRET = "test-token-secret";
50
+ });
51
+
52
+ it("returns undefined without an authorization header", async () => {
53
+ const user = await extractUserFromHeaders({}, {userModel});
54
+
55
+ expect(user).toBeUndefined();
56
+ });
57
+
58
+ it("returns undefined for an empty bearer token", async () => {
59
+ const user = await extractUserFromHeaders({authorization: "Bearer "}, {userModel});
60
+
61
+ expect(user).toBeUndefined();
62
+ });
63
+
64
+ it("resolves a user from a Bearer JWT", async () => {
65
+ const created = await UserTestModel.create({email: "jwt@example.com"});
66
+ const token = signToken({id: created._id.toString()});
67
+
68
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
69
+
70
+ expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
71
+ });
72
+
73
+ it("accepts a raw token without the Bearer prefix", async () => {
74
+ const created = await UserTestModel.create({email: "raw@example.com"});
75
+ const token = signToken({sub: created._id.toString()});
76
+
77
+ const user = await extractUserFromHeaders({authorization: token}, {userModel});
78
+
79
+ expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
80
+ });
81
+
82
+ it("uses the first value when the header is an array", async () => {
83
+ const created = await UserTestModel.create({email: "array@example.com"});
84
+ const token = signToken({id: created._id.toString()});
85
+
86
+ const user = await extractUserFromHeaders(
87
+ {authorization: [`Bearer ${token}`, "Bearer ignored"]},
88
+ {userModel}
89
+ );
90
+
91
+ expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
92
+ });
93
+
94
+ it("returns undefined when TOKEN_SECRET is unset", async () => {
95
+ Reflect.deleteProperty(process.env, "TOKEN_SECRET");
96
+ const token = signToken({id: new mongoose.Types.ObjectId().toString()});
97
+
98
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
99
+
100
+ expect(user).toBeUndefined();
101
+ });
102
+
103
+ it("returns undefined for a token signed with the wrong secret", async () => {
104
+ const token = signToken({id: new mongoose.Types.ObjectId().toString()}, "other-secret");
105
+
106
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
107
+
108
+ expect(user).toBeUndefined();
109
+ });
110
+
111
+ it("returns undefined when the token carries no user id", async () => {
112
+ const token = signToken({email: "nobody@example.com"});
113
+
114
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
115
+
116
+ expect(user).toBeUndefined();
117
+ });
118
+
119
+ it("resolves a user from a Better Auth session", async () => {
120
+ const created = await UserTestModel.create({
121
+ betterAuthId: "ba-123",
122
+ email: "better@example.com",
123
+ });
124
+ const betterAuth = fakeBetterAuth(async () => ({
125
+ session: {id: "session-1"},
126
+ user: {id: "ba-123"},
127
+ }));
128
+
129
+ const user = await extractUserFromHeaders({cookie: "session=1"}, {betterAuth, userModel});
130
+
131
+ expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
132
+ });
133
+
134
+ it("falls back to JWT when the Better Auth session has no matching app user", async () => {
135
+ const created = await UserTestModel.create({email: "fallback@example.com"});
136
+ const token = signToken({id: created._id.toString()});
137
+ const betterAuth = fakeBetterAuth(async () => ({
138
+ session: {id: "session-1"},
139
+ user: {id: "unknown-better-auth-id"},
140
+ }));
141
+
142
+ const user = await extractUserFromHeaders(
143
+ {authorization: `Bearer ${token}`},
144
+ {betterAuth, userModel}
145
+ );
146
+
147
+ expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
148
+ });
149
+
150
+ it("falls back to JWT when Better Auth session extraction throws", async () => {
151
+ const created = await UserTestModel.create({email: "throws@example.com"});
152
+ const token = signToken({id: created._id.toString()});
153
+ const betterAuth = fakeBetterAuth(async () => {
154
+ throw new Error("session lookup failed");
155
+ });
156
+
157
+ const user = await extractUserFromHeaders(
158
+ {authorization: `Bearer ${token}`},
159
+ {betterAuth, userModel}
160
+ );
161
+
162
+ expect(String((user as unknown as MCPAuthUserFields)?._id)).toBe(created._id.toString());
163
+ });
164
+
165
+ it("rejects a disabled user authenticating with a valid JWT", async () => {
166
+ const created = await UserTestModel.create({disabled: true, email: "disabled@example.com"});
167
+ const token = signToken({id: created._id.toString()});
168
+
169
+ const user = await extractUserFromHeaders({authorization: `Bearer ${token}`}, {userModel});
170
+
171
+ expect(user).toBeUndefined();
172
+ });
173
+
174
+ it("rejects a disabled user authenticating with a Better Auth session", async () => {
175
+ await UserTestModel.create({
176
+ betterAuthId: "ba-disabled",
177
+ disabled: true,
178
+ email: "disabled-ba@example.com",
179
+ });
180
+ const betterAuth = fakeBetterAuth(async () => ({
181
+ session: {id: "session-1"},
182
+ user: {id: "ba-disabled"},
183
+ }));
184
+
185
+ const user = await extractUserFromHeaders({cookie: "session=1"}, {betterAuth, userModel});
186
+
187
+ expect(user).toBeUndefined();
188
+ });
189
+
190
+ it("returns undefined when Better Auth has no session and no JWT is present", async () => {
191
+ const betterAuth = fakeBetterAuth(async () => null);
192
+
193
+ const user = await extractUserFromHeaders({}, {betterAuth, userModel});
194
+
195
+ expect(user).toBeUndefined();
196
+ });
197
+ });
@@ -0,0 +1,100 @@
1
+ import jwt from "jsonwebtoken";
2
+
3
+ import type {User, UserModel} from "../auth";
4
+ import type {BetterAuthInstance} from "../betterAuthSetup";
5
+ import {logger} from "../logger";
6
+ import {findOneOrNoneFor} from "../plugins";
7
+
8
+ export interface MCPAuthContext {
9
+ userModel: UserModel;
10
+ betterAuth?: BetterAuthInstance;
11
+ }
12
+
13
+ /**
14
+ * Reject a disabled account the way the JWT middleware's 401 does. Without this an MCP
15
+ * client could keep calling tools with a still-valid token or session after the account
16
+ * was disabled, which REST already refuses.
17
+ */
18
+ const rejectIfDisabled = (user: User | undefined, source: string): User | undefined => {
19
+ if (!user) {
20
+ return undefined;
21
+ }
22
+ if ((user as {disabled?: boolean}).disabled) {
23
+ logger.warn(`[mcp] User ${user.id} is disabled, rejecting ${source} credentials`);
24
+ return undefined;
25
+ }
26
+ return user;
27
+ };
28
+
29
+ /**
30
+ * Extract user from raw headers using whichever auth provider is configured.
31
+ * Works with both JWT and Better Auth, mirroring authenticateMiddleware behavior.
32
+ */
33
+ export const extractUserFromHeaders = async (
34
+ headers: Record<string, string | string[] | undefined>,
35
+ context: MCPAuthContext
36
+ ): Promise<User | undefined> => {
37
+ const {userModel, betterAuth} = context;
38
+
39
+ // Try Better Auth first if configured
40
+ if (betterAuth) {
41
+ try {
42
+ const session = await betterAuth.api.getSession({
43
+ headers: headers as Record<string, string>,
44
+ });
45
+
46
+ if (session?.user && session?.session) {
47
+ // betterAuthId is unique per user — findById-like lookup that may return null.
48
+ // findOneOrNoneFor keeps the repo's "never call findOne directly" convention while
49
+ // working whether or not the consumer's model has the findOneOrNone plugin applied.
50
+ const appUser = await findOneOrNoneFor(userModel, {betterAuthId: session.user.id});
51
+ if (appUser) {
52
+ return rejectIfDisabled(appUser as unknown as User, "Better Auth");
53
+ }
54
+ }
55
+ } catch (error) {
56
+ logger.debug(`MCP Better Auth session extraction failed: ${error}`);
57
+ }
58
+ }
59
+
60
+ // Try JWT auth
61
+ const authorization =
62
+ typeof headers.authorization === "string"
63
+ ? headers.authorization
64
+ : Array.isArray(headers.authorization)
65
+ ? headers.authorization[0]
66
+ : undefined;
67
+
68
+ if (!authorization) {
69
+ return undefined;
70
+ }
71
+
72
+ const token = authorization.startsWith("Bearer ") ? authorization.slice(7) : authorization;
73
+
74
+ if (!token) {
75
+ return undefined;
76
+ }
77
+
78
+ const tokenSecret = process.env.TOKEN_SECRET;
79
+ if (!tokenSecret) {
80
+ logger.warn("TOKEN_SECRET not set, cannot verify JWT for MCP request");
81
+ return undefined;
82
+ }
83
+
84
+ try {
85
+ const decoded = jwt.verify(token, tokenSecret, {
86
+ issuer: process.env.TOKEN_ISSUER,
87
+ }) as jwt.JwtPayload;
88
+
89
+ const userId = decoded.id || decoded.sub;
90
+ if (!userId) {
91
+ return undefined;
92
+ }
93
+
94
+ const user = await userModel.findById(userId);
95
+ return rejectIfDisabled(user as unknown as User | undefined, "JWT");
96
+ } catch (error) {
97
+ logger.debug(`MCP JWT verification failed: ${error}`);
98
+ return undefined;
99
+ }
100
+ };
@@ -0,0 +1,47 @@
1
+ import {describe, expect, it} from "bun:test";
2
+
3
+ import {createMCPRequest} from "./createMCPRequest";
4
+ import type {MCPRequest} from "./types";
5
+
6
+ const asMCPRequest = (req: unknown): MCPRequest => {
7
+ return req as unknown as MCPRequest;
8
+ };
9
+
10
+ describe("createMCPRequest", () => {
11
+ it("returns a stub Express-shaped request, not a real HTTP request", () => {
12
+ const user = {_id: "user-1"} as MCPRequest["user"];
13
+ const request = asMCPRequest(
14
+ createMCPRequest({
15
+ body: {title: "Hooked"},
16
+ user,
17
+ })
18
+ );
19
+
20
+ expect(request.isMCPRequest).toBe(true);
21
+ expect(request.method).toBe("MCP");
22
+ expect(request.body).toEqual({title: "Hooked"});
23
+ expect(request.headers).toEqual({});
24
+ expect(request.query).toEqual({});
25
+ expect(request.params).toEqual({});
26
+ expect(request.user).toBe(user);
27
+ expect(Object.keys(request).sort()).toEqual([
28
+ "body",
29
+ "headers",
30
+ "isMCPRequest",
31
+ "method",
32
+ "params",
33
+ "query",
34
+ "user",
35
+ ]);
36
+ });
37
+
38
+ it("defaults missing body to {} and omits user", () => {
39
+ const request = asMCPRequest(createMCPRequest({}));
40
+
41
+ expect(request.body).toEqual({});
42
+ expect(request.user).toBeUndefined();
43
+ expect(request.headers).toEqual({});
44
+ expect(request.query).toEqual({});
45
+ expect(request.params).toEqual({});
46
+ });
47
+ });
@@ -0,0 +1,32 @@
1
+ import type express from "express";
2
+
3
+ import type {User} from "../auth";
4
+ import type {MCPRequest, MCPToolArgs} from "./types";
5
+
6
+ /**
7
+ * Build the Express-shaped request handed to lifecycle hooks and response handlers.
8
+ *
9
+ * An MCP tool call is JSON-RPC, not HTTP, so there is no real request to forward. The
10
+ * authenticated user is the only field with a genuine equivalent — everything else is
11
+ * filled in with empty defaults so hooks that read `req.body`, `req.query`, `req.params`,
12
+ * or `req.headers` get the shape they expect instead of a TypeError. `isMCPRequest` lets
13
+ * a hook detect the MCP path when it needs to behave differently from HTTP.
14
+ */
15
+ export const createMCPRequest = ({
16
+ body = {},
17
+ user,
18
+ }: {
19
+ body?: MCPToolArgs;
20
+ user?: User;
21
+ }): express.Request => {
22
+ const request: MCPRequest = {
23
+ body,
24
+ headers: {},
25
+ isMCPRequest: true,
26
+ method: "MCP",
27
+ params: {},
28
+ query: {},
29
+ user,
30
+ };
31
+ return request as unknown as express.Request;
32
+ };
@@ -0,0 +1,54 @@
1
+ import {beforeEach, describe, expect, it} from "bun:test";
2
+ import {z} from "zod";
3
+
4
+ import type {User} from "../auth";
5
+ import {clearMCPRegistry, registerMCPTool} from "./registry";
6
+ import {getAllMCPTools} from "./toolGenerator";
7
+
8
+ describe("registerMCPTool", () => {
9
+ beforeEach(() => {
10
+ clearMCPRegistry();
11
+ });
12
+
13
+ it("includes custom tools in getAllMCPTools", async () => {
14
+ registerMCPTool({
15
+ description: "Echo a message",
16
+ handler: async (args) => {
17
+ return {
18
+ content: [{text: JSON.stringify({echo: args.message}), type: "text"}],
19
+ };
20
+ },
21
+ name: "echo_message",
22
+ zodSchema: z.object({message: z.string()}).strict(),
23
+ });
24
+
25
+ const tools = getAllMCPTools();
26
+ expect(tools.map((tool) => tool.name)).toEqual(["echo_message"]);
27
+
28
+ const result = await tools[0].handler({message: "hi"}, {_id: "u1"} as unknown as User);
29
+ expect(JSON.parse(result.content[0].text)).toEqual({echo: "hi"});
30
+ });
31
+
32
+ it("replaces a custom tool registered with the same name", () => {
33
+ registerMCPTool({
34
+ description: "first",
35
+ handler: async () => {
36
+ return {content: [{text: "first", type: "text"}]};
37
+ },
38
+ name: "echo_message",
39
+ zodSchema: z.object({}).strict(),
40
+ });
41
+ registerMCPTool({
42
+ description: "second",
43
+ handler: async () => {
44
+ return {content: [{text: "second", type: "text"}]};
45
+ },
46
+ name: "echo_message",
47
+ zodSchema: z.object({}).strict(),
48
+ });
49
+
50
+ const tools = getAllMCPTools();
51
+ expect(tools).toHaveLength(1);
52
+ expect(tools[0].description).toBe("second");
53
+ });
54
+ });