@terreno/api 57.16.2 → 57.18.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.
- package/dist/actions.d.ts +26 -3
- package/dist/actions.js +102 -16
- package/dist/api.d.ts +7 -0
- package/dist/api.js +59 -3
- package/dist/auth.d.ts +28 -4
- package/dist/auth.js +140 -15
- package/dist/authRecovery.d.ts +31 -0
- package/dist/authRecovery.js +86 -6
- package/dist/betterAuth.d.ts +86 -0
- package/dist/betterAuthApp.d.ts +17 -0
- package/dist/betterAuthApp.js +12 -1
- package/dist/betterAuthOAuthHandoff.d.ts +24 -0
- package/dist/betterAuthOAuthHandoff.js +305 -0
- package/dist/betterAuthSetup.d.ts +37 -2
- package/dist/betterAuthSetup.js +304 -24
- package/dist/expressServer.d.ts +16 -0
- package/dist/expressServer.js +61 -14
- package/dist/githubAuth.d.ts +9 -0
- package/dist/githubAuth.js +230 -31
- package/dist/index.d.ts +9 -1
- package/dist/index.js +27 -3
- package/dist/mcp/actionTools.d.ts +4 -0
- package/dist/mcp/actionTools.js +158 -0
- package/dist/mcp/auth.d.ts +30 -0
- package/dist/mcp/auth.js +83 -28
- package/dist/mcp/createMCPRequest.d.ts +5 -1
- package/dist/mcp/createMCPRequest.js +3 -3
- package/dist/mcp/handlers.d.ts +3 -0
- package/dist/mcp/handlers.js +43 -27
- package/dist/mcp/oauth.d.ts +14 -0
- package/dist/mcp/oauth.js +618 -0
- package/dist/mcp/oauthMetadata.d.ts +89 -0
- package/dist/mcp/oauthMetadata.js +137 -0
- package/dist/mcp/registry.d.ts +5 -0
- package/dist/mcp/registry.js +9 -1
- package/dist/mcp/server.d.ts +6 -0
- package/dist/mcp/server.js +44 -7
- package/dist/mcp/serviceTokens.js +12 -2
- package/dist/mcp/toolExecution.d.ts +12 -0
- package/dist/mcp/toolExecution.js +60 -0
- package/dist/mcp/toolGenerator.d.ts +4 -1
- package/dist/mcp/toolGenerator.js +26 -60
- package/dist/mcp/types.d.ts +4 -4
- package/dist/models/mcpOAuthAuthorization.d.ts +2 -0
- package/dist/models/mcpOAuthAuthorization.js +86 -0
- package/dist/models/mcpOAuthClient.d.ts +2 -0
- package/dist/models/mcpOAuthClient.js +42 -0
- package/dist/models/mcpOAuthRevokedFamily.d.ts +2 -0
- package/dist/models/mcpOAuthRevokedFamily.js +36 -0
- package/dist/models/mcpOAuthToken.d.ts +12 -0
- package/dist/models/mcpOAuthToken.js +159 -0
- package/dist/models/mcpServiceToken.d.ts +1 -0
- package/dist/models/mcpServiceToken.js +21 -4
- package/dist/permissions.d.ts +7 -0
- package/dist/permissions.js +18 -1
- package/dist/rateLimit/policies.d.ts +4 -0
- package/dist/rateLimit/policies.js +46 -7
- package/dist/rbac/access.js +1 -0
- package/dist/rbac/membershipOrgAdminSource.d.ts +4 -0
- package/dist/rbac/membershipOrgAdminSource.js +5 -0
- package/dist/rbac/modelRouterAccess.d.ts +7 -1
- package/dist/rbac/modelRouterAccess.js +37 -24
- package/dist/rbac/realtimeAccess.js +17 -3
- package/dist/rbac/resolve.js +66 -9
- package/dist/rbac/roleManager.js +60 -5
- package/dist/rbac/roleModel.js +1 -1
- package/dist/rbac/statements.d.ts +1 -1
- package/dist/rbac/statements.js +13 -1
- package/dist/rbac/types.d.ts +12 -0
- package/dist/rbac/userWriteGuards.d.ts +50 -0
- package/dist/rbac/userWriteGuards.js +156 -0
- package/dist/realtime/changeStreamWatcher.d.ts +4 -1
- package/dist/realtime/changeStreamWatcher.js +157 -73
- package/dist/realtime/queryMatcher.d.ts +3 -0
- package/dist/realtime/queryMatcher.js +25 -10
- package/dist/realtime/realtimeApp.d.ts +16 -1
- package/dist/realtime/realtimeApp.js +76 -8
- package/dist/realtime/socketAuth.d.ts +17 -6
- package/dist/realtime/socketAuth.js +77 -16
- package/dist/realtime/types.d.ts +8 -5
- package/dist/requestContext.d.ts +22 -0
- package/dist/requestContext.js +22 -1
- package/dist/seedRunner.js +3 -1
- package/dist/sortFields.d.ts +33 -0
- package/dist/sortFields.js +55 -0
- package/dist/sync/executors.js +140 -2
- package/dist/sync/models.d.ts +2 -0
- package/dist/sync/models.js +5 -0
- package/dist/sync/mutationHandler.js +70 -7
- package/dist/sync/routes.js +4 -2
- package/dist/sync/syncSeqPlugin.js +6 -5
- package/dist/terrenoApp.d.ts +14 -0
- package/dist/terrenoApp.js +21 -6
- package/dist/types/mcpOAuth.d.ts +101 -0
- package/dist/types/mcpOAuth.js +2 -0
- package/dist/types/mcpServiceToken.d.ts +8 -0
- package/package.json +3 -3
- package/src/actions.test.ts +118 -0
- package/src/actions.ts +139 -17
- package/src/api.arrayOperations.test.ts +78 -0
- package/src/api.test.ts +36 -0
- package/src/api.ts +76 -4
- package/src/auth.test.ts +521 -3
- package/src/auth.ts +171 -17
- package/src/authRecovery.test.ts +99 -0
- package/src/authRecovery.ts +117 -5
- package/src/authVerification.test.ts +3 -3
- package/src/betterAuth.ts +104 -1
- package/src/betterAuthApp.test.ts +634 -1
- package/src/betterAuthApp.ts +28 -0
- package/src/betterAuthOAuthHandoff.test.ts +946 -0
- package/src/betterAuthOAuthHandoff.ts +375 -0
- package/src/betterAuthSetup.test.ts +393 -4
- package/src/betterAuthSetup.ts +402 -29
- package/src/expressServer.test.ts +93 -0
- package/src/expressServer.ts +81 -14
- package/src/githubAuth.test.ts +448 -6
- package/src/githubAuth.ts +276 -34
- package/src/index.ts +35 -1
- package/src/mcp/actionTools.test.ts +498 -0
- package/src/mcp/actionTools.ts +220 -0
- package/src/mcp/auth.test.ts +114 -1
- package/src/mcp/auth.ts +122 -35
- package/src/mcp/createMCPRequest.ts +8 -2
- package/src/mcp/handlers.test.ts +27 -0
- package/src/mcp/handlers.ts +21 -6
- package/src/mcp/oauth.test.ts +1026 -0
- package/src/mcp/oauth.ts +798 -0
- package/src/mcp/oauthMetadata.ts +234 -0
- package/src/mcp/registry.ts +11 -0
- package/src/mcp/server.ts +54 -14
- package/src/mcp/serviceTokens.ts +16 -3
- package/src/mcp/toolExecution.ts +67 -0
- package/src/mcp/toolGenerator.ts +27 -83
- package/src/mcp/types.ts +4 -4
- package/src/models/mcpOAuthAuthorization.ts +97 -0
- package/src/models/mcpOAuthClient.ts +49 -0
- package/src/models/mcpOAuthRevokedFamily.ts +47 -0
- package/src/models/mcpOAuthToken.test.ts +82 -0
- package/src/models/mcpOAuthToken.ts +195 -0
- package/src/models/mcpServiceToken.ts +26 -2
- package/src/permissions.ts +17 -0
- package/src/rateLimit/policies.ts +54 -10
- package/src/rateLimit/rateLimit.test.ts +41 -0
- package/src/rbac/access.ts +1 -0
- package/src/rbac/membershipOrgAdminSource.ts +5 -0
- package/src/rbac/modelRouterAccess.ts +40 -23
- package/src/rbac/realtimeAccess.test.ts +43 -0
- package/src/rbac/realtimeAccess.ts +23 -3
- package/src/rbac/resolve.test.ts +179 -1
- package/src/rbac/resolve.ts +78 -9
- package/src/rbac/roleManager.test.ts +132 -0
- package/src/rbac/roleManager.ts +69 -5
- package/src/rbac/roleModel.ts +1 -1
- package/src/rbac/statements.ts +14 -1
- package/src/rbac/types.ts +12 -0
- package/src/rbac/userWriteGuards.test.ts +407 -0
- package/src/rbac/userWriteGuards.ts +185 -0
- package/src/realtime/changeStreamWatcher.ts +203 -75
- package/src/realtime/queryMatcher.ts +30 -13
- package/src/realtime/realtime.test.ts +132 -0
- package/src/realtime/realtimeApp.ts +94 -10
- package/src/realtime/realtimeAppSetup.test.ts +282 -1
- package/src/realtime/socketAuth.test.ts +140 -8
- package/src/realtime/socketAuth.ts +90 -19
- package/src/realtime/types.ts +8 -5
- package/src/requestContext.ts +52 -1
- package/src/requestCredential.test.ts +89 -0
- package/src/seedRunner.test.ts +21 -0
- package/src/seedRunner.ts +3 -1
- package/src/sortFields.ts +69 -0
- package/src/sync/executors.test.ts +382 -3
- package/src/sync/executors.ts +179 -4
- package/src/sync/models.ts +8 -0
- package/src/sync/mutationHandler.test.ts +166 -2
- package/src/sync/mutationHandler.ts +97 -5
- package/src/sync/routes.ts +4 -2
- package/src/sync/syncFrontier.test.ts +11 -0
- package/src/sync/syncPhaseC.test.ts +18 -0
- package/src/sync/syncSeqPlugin.ts +6 -5
- package/src/sync/syncSocket.test.ts +92 -0
- package/src/terrenoApp.ts +36 -21
- package/src/types/mcpOAuth.ts +129 -0
- package/src/types/mcpServiceToken.ts +6 -1
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import type {Request, Response} from "express";
|
|
2
|
+
import type {Model} from "mongoose";
|
|
3
|
+
import {toJSONSchema, type ZodObject, type ZodType, z} from "zod";
|
|
4
|
+
|
|
5
|
+
import {
|
|
6
|
+
type ActionContext,
|
|
7
|
+
type ActionScope,
|
|
8
|
+
type BaseActionConfig,
|
|
9
|
+
type CollectionActionConfig,
|
|
10
|
+
type InstanceActionConfig,
|
|
11
|
+
runActionPermissions,
|
|
12
|
+
} from "../actions";
|
|
13
|
+
import type {ModelRouterOptions} from "../api";
|
|
14
|
+
import type {User} from "../auth";
|
|
15
|
+
import type {CollectionRecord} from "../collectionRegistry";
|
|
16
|
+
import {loadDocOr404} from "../docLoader";
|
|
17
|
+
import {APIError, isAPIError} from "../errors";
|
|
18
|
+
import {createMCPRequest} from "./createMCPRequest";
|
|
19
|
+
import {errorMessage, errorResult, textResult} from "./handlers";
|
|
20
|
+
import {executeTool} from "./toolExecution";
|
|
21
|
+
import type {MCPToolDefinition} from "./toolGenerator";
|
|
22
|
+
import type {MCPToolArgs, MCPToolInputSchema, MCPToolResult} from "./types";
|
|
23
|
+
|
|
24
|
+
type AnyActionConfig =
|
|
25
|
+
| InstanceActionConfig<unknown, unknown, unknown, unknown>
|
|
26
|
+
| CollectionActionConfig<unknown, unknown, unknown>;
|
|
27
|
+
|
|
28
|
+
interface MCPActionEntry {
|
|
29
|
+
actionName: string;
|
|
30
|
+
config: AnyActionConfig;
|
|
31
|
+
model: Model<unknown>;
|
|
32
|
+
options: ModelRouterOptions<unknown>;
|
|
33
|
+
scope: ActionScope;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Stands in for `res` during an MCP call. MCP returns the handler's value as the tool result,
|
|
38
|
+
* so a handler that writes to `res` has nowhere to send it; failing loudly beats a silent drop.
|
|
39
|
+
*/
|
|
40
|
+
const createMCPResponseStub = (toolName: string): Response => {
|
|
41
|
+
return new Proxy({} as Response, {
|
|
42
|
+
get: (_target, property) => {
|
|
43
|
+
// Inspectors and promise checks probe symbols; only real field access is an error.
|
|
44
|
+
if (typeof property === "symbol") {
|
|
45
|
+
return undefined;
|
|
46
|
+
}
|
|
47
|
+
throw new APIError({
|
|
48
|
+
code: "mcp-action-touched-response",
|
|
49
|
+
detail: `The action behind MCP tool "${toolName}" read res.${property}. Return a value instead of writing to res, or leave mcp off this action.`,
|
|
50
|
+
status: 500,
|
|
51
|
+
title: "Action used res during an MCP call",
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const ID_SCHEMA = z.string().describe("Id of the document to run the action on");
|
|
58
|
+
|
|
59
|
+
/** `{id}` merged with the body (POST) or query (GET) schema; collection actions have no id. */
|
|
60
|
+
const buildActionInputSchema = (scope: ActionScope, config: AnyActionConfig): ZodType => {
|
|
61
|
+
const idShape: Record<string, ZodType> = scope === "instance" ? {id: ID_SCHEMA} : {};
|
|
62
|
+
const argsSchema = config.method === "GET" ? config.query : config.body;
|
|
63
|
+
if (!argsSchema) {
|
|
64
|
+
// No schema: REST forwards the raw body, so the tool accepts any extra arguments too.
|
|
65
|
+
return z.looseObject(idShape);
|
|
66
|
+
}
|
|
67
|
+
// safeExtend keeps refinements on the action's schema; registration checked it is an object.
|
|
68
|
+
return (argsSchema as unknown as ZodObject).safeExtend(idShape);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Expected refusals carry no cause, so the audit log records them as warnings. */
|
|
72
|
+
const toolErrorFromException = (error: unknown): MCPToolResult => {
|
|
73
|
+
if (!isAPIError(error)) {
|
|
74
|
+
return errorResult(errorMessage(error), error);
|
|
75
|
+
}
|
|
76
|
+
const fieldErrors = error.meta?.fields as Record<string, string> | undefined;
|
|
77
|
+
const fields = fieldErrors
|
|
78
|
+
? Object.entries(fieldErrors)
|
|
79
|
+
.map(([field, message]) => `${field}: ${message}`)
|
|
80
|
+
.join("; ")
|
|
81
|
+
: undefined;
|
|
82
|
+
const message = fields ? `${error.title} (${fields})` : error.title;
|
|
83
|
+
return (error.status ?? 500) < 500 ? errorResult(message) : errorResult(message, error);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const isAuthenticationRequired = (entry: MCPActionEntry, user?: User): boolean => {
|
|
87
|
+
return !user && !(entry.config.allowAnonymous ?? entry.options.allowAnonymous);
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Run an action the way REST does: pre-document permissions, load the document and re-check
|
|
92
|
+
* (instance actions), then the handler. The MCP server already validated `args` against the
|
|
93
|
+
* action's zod schema, so the parsed values go to the handler as-is.
|
|
94
|
+
*/
|
|
95
|
+
const runActionTool = async (
|
|
96
|
+
entry: MCPActionEntry,
|
|
97
|
+
toolName: string,
|
|
98
|
+
args: MCPToolArgs,
|
|
99
|
+
user?: User
|
|
100
|
+
): Promise<MCPToolResult> => {
|
|
101
|
+
const {config, model, options, scope} = entry;
|
|
102
|
+
if (isAuthenticationRequired(entry, user)) {
|
|
103
|
+
return errorResult("Permission denied: authentication required");
|
|
104
|
+
}
|
|
105
|
+
// Only instance tools add `id`; a collection action's own schema may define one for its body.
|
|
106
|
+
const {id, ...instanceInput} = args;
|
|
107
|
+
const input = scope === "instance" ? instanceInput : args;
|
|
108
|
+
const isGet = config.method === "GET";
|
|
109
|
+
const req = createMCPRequest({
|
|
110
|
+
body: isGet ? {} : input,
|
|
111
|
+
params: scope === "instance" ? {id: String(id)} : {},
|
|
112
|
+
query: isGet ? input : {},
|
|
113
|
+
user,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
await runActionPermissions(
|
|
118
|
+
config as BaseActionConfig<unknown, unknown, unknown>,
|
|
119
|
+
scope,
|
|
120
|
+
model,
|
|
121
|
+
req,
|
|
122
|
+
undefined,
|
|
123
|
+
options.accessControl,
|
|
124
|
+
options.access
|
|
125
|
+
);
|
|
126
|
+
let doc: unknown;
|
|
127
|
+
if (scope === "instance") {
|
|
128
|
+
doc = await loadDocOr404(model, String(id), options.populatePaths);
|
|
129
|
+
(req as Request & {obj?: unknown}).obj = doc;
|
|
130
|
+
await runActionPermissions(
|
|
131
|
+
config as BaseActionConfig<unknown, unknown, unknown>,
|
|
132
|
+
scope,
|
|
133
|
+
model,
|
|
134
|
+
req,
|
|
135
|
+
doc,
|
|
136
|
+
options.accessControl,
|
|
137
|
+
options.access
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const ctx = {
|
|
142
|
+
body: req.body,
|
|
143
|
+
doc,
|
|
144
|
+
query: req.query,
|
|
145
|
+
req,
|
|
146
|
+
res: createMCPResponseStub(toolName),
|
|
147
|
+
user: req.user,
|
|
148
|
+
};
|
|
149
|
+
const result =
|
|
150
|
+
scope === "instance"
|
|
151
|
+
? await (config as InstanceActionConfig<unknown, unknown, unknown, unknown>).handler(
|
|
152
|
+
ctx as ActionContext<unknown, unknown, unknown>
|
|
153
|
+
)
|
|
154
|
+
: await (config as CollectionActionConfig<unknown, unknown, unknown>).handler(
|
|
155
|
+
ctx as Omit<ActionContext<never, unknown, unknown>, "doc">
|
|
156
|
+
);
|
|
157
|
+
return textResult(JSON.stringify(result ?? null));
|
|
158
|
+
} catch (error) {
|
|
159
|
+
return toolErrorFromException(error);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const isDisabled = (config: AnyActionConfig): boolean => {
|
|
164
|
+
return config.permissions !== undefined && config.permissions.length === 0 && !config.access;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
const listMCPActions = (record: CollectionRecord): MCPActionEntry[] => {
|
|
168
|
+
const {model, options} = record;
|
|
169
|
+
const entries: MCPActionEntry[] = [];
|
|
170
|
+
const scopes: [ActionScope, Record<string, AnyActionConfig> | undefined][] = [
|
|
171
|
+
["instance", options.instanceActions as Record<string, AnyActionConfig> | undefined],
|
|
172
|
+
["collection", options.collectionActions as Record<string, AnyActionConfig> | undefined],
|
|
173
|
+
];
|
|
174
|
+
for (const [scope, actions] of scopes) {
|
|
175
|
+
for (const [actionName, config] of Object.entries(actions ?? {})) {
|
|
176
|
+
if (config.mcp && !isDisabled(config)) {
|
|
177
|
+
entries.push({actionName, config, model, options, scope});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return entries;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const describeAction = (entry: MCPActionEntry): string => {
|
|
185
|
+
const {actionName, config, model, scope} = entry;
|
|
186
|
+
const base =
|
|
187
|
+
config.mcp?.description ??
|
|
188
|
+
config.description ??
|
|
189
|
+
config.summary ??
|
|
190
|
+
`Run the ${actionName} action on ${model.modelName}`;
|
|
191
|
+
return scope === "instance" ? `${base} (pass the ${model.modelName} id as "id")` : base;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/** MCP tools for every modelRouter action that sets `mcp`, across all registered routers. */
|
|
195
|
+
export const generateActionTools = (records: CollectionRecord[]): MCPToolDefinition[] => {
|
|
196
|
+
const tools: MCPToolDefinition[] = [];
|
|
197
|
+
for (const record of records) {
|
|
198
|
+
for (const entry of listMCPActions(record)) {
|
|
199
|
+
const toolName = entry.config.mcp?.name as string;
|
|
200
|
+
const zodSchema = buildActionInputSchema(entry.scope, entry.config);
|
|
201
|
+
tools.push({
|
|
202
|
+
description: describeAction(entry),
|
|
203
|
+
handler: (args: MCPToolArgs, user?: User) =>
|
|
204
|
+
executeTool({
|
|
205
|
+
labels: {
|
|
206
|
+
mcpAction: entry.actionName,
|
|
207
|
+
mcpModel: entry.model.modelName,
|
|
208
|
+
mcpTool: toolName,
|
|
209
|
+
},
|
|
210
|
+
run: () => runActionTool(entry, toolName, args, user),
|
|
211
|
+
user,
|
|
212
|
+
}),
|
|
213
|
+
inputSchema: toJSONSchema(zodSchema) as MCPToolInputSchema,
|
|
214
|
+
name: toolName,
|
|
215
|
+
zodSchema,
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return tools;
|
|
220
|
+
};
|
package/src/mcp/auth.test.ts
CHANGED
|
@@ -1,25 +1,29 @@
|
|
|
1
1
|
import {beforeEach, describe, expect, it, spyOn} from "bun:test";
|
|
2
2
|
import {assert} from "chai";
|
|
3
3
|
import jwt from "jsonwebtoken";
|
|
4
|
+
import {DateTime} from "luxon";
|
|
4
5
|
import mongoose, {Schema} from "mongoose";
|
|
5
6
|
|
|
6
7
|
import type {UserModel} from "../auth";
|
|
7
8
|
import type {BetterAuthInstance} from "../betterAuthSetup";
|
|
9
|
+
import {McpOAuthToken} from "../models/mcpOAuthToken";
|
|
8
10
|
import {McpServiceToken} from "../models/mcpServiceToken";
|
|
9
11
|
import {findOneOrNone} from "../plugins";
|
|
10
|
-
import {extractUserFromHeaders} from "./auth";
|
|
12
|
+
import {extractAuthFromHeaders, extractUserFromHeaders} from "./auth";
|
|
11
13
|
|
|
12
14
|
interface MCPAuthUserFields {
|
|
13
15
|
_id: mongoose.Types.ObjectId;
|
|
14
16
|
betterAuthId?: string;
|
|
15
17
|
disabled?: boolean;
|
|
16
18
|
email?: string;
|
|
19
|
+
tokenEpoch?: number;
|
|
17
20
|
}
|
|
18
21
|
|
|
19
22
|
const userSchema = new Schema({
|
|
20
23
|
betterAuthId: {description: "Better Auth user id", index: true, type: String},
|
|
21
24
|
disabled: {default: false, description: "Whether the account is disabled", type: Boolean},
|
|
22
25
|
email: {description: "User email", type: String},
|
|
26
|
+
tokenEpoch: {description: "Credential generation", type: Number},
|
|
23
27
|
});
|
|
24
28
|
userSchema.plugin(findOneOrNone);
|
|
25
29
|
|
|
@@ -102,6 +106,43 @@ describe("extractUserFromHeaders", () => {
|
|
|
102
106
|
assert.isUndefined(user);
|
|
103
107
|
});
|
|
104
108
|
|
|
109
|
+
it("treats a service token stored without tokenEpoch as epoch 0", async () => {
|
|
110
|
+
const created = await UserTestModel.create({email: "legacy-mcp-token@example.com"});
|
|
111
|
+
const issued = await McpServiceToken.issueFor({_id: created._id}, {name: "Legacy"});
|
|
112
|
+
await McpServiceToken.updateOne({_id: issued.mcpServiceToken._id}, {$unset: {tokenEpoch: 1}});
|
|
113
|
+
const headers = {authorization: `Bearer ${issued.token}`};
|
|
114
|
+
|
|
115
|
+
const before = await extractUserFromHeaders(headers, {mcpServiceTokens: true, userModel});
|
|
116
|
+
await UserTestModel.updateOne({_id: created._id}, {$set: {tokenEpoch: 1}});
|
|
117
|
+
const after = await extractUserFromHeaders(headers, {mcpServiceTokens: true, userModel});
|
|
118
|
+
|
|
119
|
+
assert.equal(String((before as unknown as MCPAuthUserFields)?._id), created._id.toString());
|
|
120
|
+
assert.isUndefined(after);
|
|
121
|
+
const stored = await McpServiceToken.findById(issued.mcpServiceToken._id);
|
|
122
|
+
assert.isDefined(stored?.revokedAt);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("rejects and revokes a service token issued under an earlier tokenEpoch", async () => {
|
|
126
|
+
const created = await UserTestModel.create({
|
|
127
|
+
email: "epoch-mcp-token@example.com",
|
|
128
|
+
tokenEpoch: 2,
|
|
129
|
+
});
|
|
130
|
+
const issued = await McpServiceToken.issueFor(
|
|
131
|
+
{_id: created._id, tokenEpoch: 2},
|
|
132
|
+
{name: "Epoch"}
|
|
133
|
+
);
|
|
134
|
+
const headers = {authorization: `Bearer ${issued.token}`};
|
|
135
|
+
|
|
136
|
+
const before = await extractUserFromHeaders(headers, {mcpServiceTokens: true, userModel});
|
|
137
|
+
await UserTestModel.updateOne({_id: created._id}, {$inc: {tokenEpoch: 1}});
|
|
138
|
+
const after = await extractUserFromHeaders(headers, {mcpServiceTokens: true, userModel});
|
|
139
|
+
|
|
140
|
+
assert.isDefined(before);
|
|
141
|
+
assert.isUndefined(after);
|
|
142
|
+
const stored = await McpServiceToken.findById(issued.mcpServiceToken._id);
|
|
143
|
+
assert.isDefined(stored?.revokedAt);
|
|
144
|
+
});
|
|
145
|
+
|
|
105
146
|
it("rejects MCP service tokens belonging to disabled users", async () => {
|
|
106
147
|
const created = await UserTestModel.create({
|
|
107
148
|
disabled: true,
|
|
@@ -275,3 +316,75 @@ describe("extractUserFromHeaders", () => {
|
|
|
275
316
|
expect(user).toBeUndefined();
|
|
276
317
|
});
|
|
277
318
|
});
|
|
319
|
+
|
|
320
|
+
describe("extractAuthFromHeaders", () => {
|
|
321
|
+
beforeEach(async () => {
|
|
322
|
+
await UserTestModel.deleteMany({});
|
|
323
|
+
await McpOAuthToken.deleteMany({});
|
|
324
|
+
process.env.TOKEN_SECRET = "test-token-secret";
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
const issueOAuthToken = async (userId: mongoose.Types.ObjectId): Promise<string> => {
|
|
328
|
+
const issued = await McpOAuthToken.issue({
|
|
329
|
+
accessTokenTtlSeconds: 60,
|
|
330
|
+
clientId: "client",
|
|
331
|
+
refreshTokenTtlSeconds: 600,
|
|
332
|
+
userId,
|
|
333
|
+
});
|
|
334
|
+
return issued.accessToken;
|
|
335
|
+
};
|
|
336
|
+
|
|
337
|
+
it("reports jwt for a JWT bearer", async () => {
|
|
338
|
+
const created = await UserTestModel.create({email: "jwt@example.com"});
|
|
339
|
+
|
|
340
|
+
const auth = await extractAuthFromHeaders(
|
|
341
|
+
{authorization: `Bearer ${signToken({id: String(created._id)})}`},
|
|
342
|
+
{userModel}
|
|
343
|
+
);
|
|
344
|
+
|
|
345
|
+
expect(auth?.credential).toBe("jwt");
|
|
346
|
+
expect(String(auth?.user._id)).toBe(String(created._id));
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it("reports better-auth-session for a Better Auth session", async () => {
|
|
350
|
+
await UserTestModel.create({betterAuthId: "ba-1", email: "ba@example.com"});
|
|
351
|
+
const betterAuth = fakeBetterAuth(async () => ({session: {id: "s"}, user: {id: "ba-1"}}));
|
|
352
|
+
|
|
353
|
+
const auth = await extractAuthFromHeaders({cookie: "session=1"}, {betterAuth, userModel});
|
|
354
|
+
|
|
355
|
+
expect(auth?.credential).toBe("better-auth-session");
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
it("resolves an OAuth access token to its user only when mcpOAuth is on", async () => {
|
|
359
|
+
const created = await UserTestModel.create({email: "oauth@example.com"});
|
|
360
|
+
const token = await issueOAuthToken(created._id);
|
|
361
|
+
const headers = {authorization: `Bearer ${token}`};
|
|
362
|
+
|
|
363
|
+
const off = await extractAuthFromHeaders(headers, {userModel});
|
|
364
|
+
const on = await extractAuthFromHeaders(headers, {mcpOAuth: true, userModel});
|
|
365
|
+
|
|
366
|
+
expect(off).toBeUndefined();
|
|
367
|
+
expect(on?.credential).toBe("oauth");
|
|
368
|
+
expect(String(on?.user._id)).toBe(String(created._id));
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
it("rejects a revoked OAuth access token and a disabled user's token", async () => {
|
|
372
|
+
const revokedUser = await UserTestModel.create({email: "revoked@example.com"});
|
|
373
|
+
const revokedToken = await issueOAuthToken(revokedUser._id);
|
|
374
|
+
await McpOAuthToken.updateMany({}, {$set: {revokedAt: DateTime.now().toJSDate()}});
|
|
375
|
+
const disabledUser = await UserTestModel.create({disabled: true, email: "off@example.com"});
|
|
376
|
+
const disabledToken = await issueOAuthToken(disabledUser._id);
|
|
377
|
+
|
|
378
|
+
const revoked = await extractAuthFromHeaders(
|
|
379
|
+
{authorization: `Bearer ${revokedToken}`},
|
|
380
|
+
{mcpOAuth: true, userModel}
|
|
381
|
+
);
|
|
382
|
+
const disabled = await extractAuthFromHeaders(
|
|
383
|
+
{authorization: `Bearer ${disabledToken}`},
|
|
384
|
+
{mcpOAuth: true, userModel}
|
|
385
|
+
);
|
|
386
|
+
|
|
387
|
+
expect(revoked).toBeUndefined();
|
|
388
|
+
expect(disabled).toBeUndefined();
|
|
389
|
+
});
|
|
390
|
+
});
|
package/src/mcp/auth.ts
CHANGED
|
@@ -4,13 +4,25 @@ import {DateTime} from "luxon";
|
|
|
4
4
|
import type {User, UserModel} from "../auth";
|
|
5
5
|
import type {BetterAuthInstance} from "../betterAuthSetup";
|
|
6
6
|
import {logger} from "../logger";
|
|
7
|
-
import {
|
|
7
|
+
import {MCP_OAUTH_ACCESS_TOKEN_PREFIX, McpOAuthToken} from "../models/mcpOAuthToken";
|
|
8
|
+
import {MCP_SERVICE_TOKEN_PREFIX, McpServiceToken} from "../models/mcpServiceToken";
|
|
8
9
|
import {findOneOrNoneFor} from "../plugins";
|
|
10
|
+
import type {RequestCredential} from "../requestContext";
|
|
9
11
|
|
|
10
12
|
export interface MCPAuthContext {
|
|
11
13
|
userModel: UserModel;
|
|
12
14
|
betterAuth?: BetterAuthInstance;
|
|
13
15
|
mcpServiceTokens?: boolean;
|
|
16
|
+
/** Accept `mcpat_` OAuth access tokens issued by the MCP OAuth server. */
|
|
17
|
+
mcpOAuth?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The authenticated user plus the credential type that proved it. */
|
|
21
|
+
export interface MCPAuthResult {
|
|
22
|
+
credential: RequestCredential;
|
|
23
|
+
/** Scopes granted to an MCP OAuth access token; unset for other credentials. */
|
|
24
|
+
scopes?: string[];
|
|
25
|
+
user: User;
|
|
14
26
|
}
|
|
15
27
|
|
|
16
28
|
/**
|
|
@@ -29,15 +41,23 @@ const rejectIfDisabled = (user: User | undefined, source: string): User | undefi
|
|
|
29
41
|
return user;
|
|
30
42
|
};
|
|
31
43
|
|
|
44
|
+
/** The user's credential generation; a password reset or session revocation increments it. */
|
|
45
|
+
export const userTokenEpoch = (user: unknown): number => {
|
|
46
|
+
const tokenEpoch = (user as {tokenEpoch?: unknown} | null | undefined)?.tokenEpoch;
|
|
47
|
+
return typeof tokenEpoch === "number" ? tokenEpoch : 0;
|
|
48
|
+
};
|
|
49
|
+
|
|
32
50
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
51
|
+
* True when a credential minted under `issuedEpoch` predates the user's current tokenEpoch.
|
|
52
|
+
* A credential stored before the field existed counts as epoch 0, as a refresh token without
|
|
53
|
+
* `te` does.
|
|
35
54
|
*/
|
|
36
|
-
export const
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
55
|
+
export const isCredentialEpochStale = (issuedEpoch: number | undefined, user: unknown): boolean =>
|
|
56
|
+
(issuedEpoch ?? 0) !== userTokenEpoch(user);
|
|
57
|
+
|
|
58
|
+
export const bearerFromHeaders = (
|
|
59
|
+
headers: Record<string, string | string[] | undefined>
|
|
60
|
+
): {authorization?: string; token?: string} => {
|
|
41
61
|
const authorization =
|
|
42
62
|
typeof headers.authorization === "string"
|
|
43
63
|
? headers.authorization
|
|
@@ -45,28 +65,86 @@ export const extractUserFromHeaders = async (
|
|
|
45
65
|
? headers.authorization[0]
|
|
46
66
|
: undefined;
|
|
47
67
|
const token = authorization?.startsWith("Bearer ") ? authorization.slice(7) : authorization;
|
|
68
|
+
return {authorization, token};
|
|
69
|
+
};
|
|
48
70
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
71
|
+
const authenticateServiceToken = async (
|
|
72
|
+
token: string,
|
|
73
|
+
userModel: UserModel
|
|
74
|
+
): Promise<MCPAuthResult | undefined> => {
|
|
75
|
+
const serviceToken = await McpServiceToken.verify(token);
|
|
76
|
+
if (!serviceToken) {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
const user = await userModel.findById(serviceToken.userId);
|
|
80
|
+
const activeUser = rejectIfDisabled(user as unknown as User | undefined, "MCP service token");
|
|
81
|
+
if (!activeUser) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
if (isCredentialEpochStale(serviceToken.tokenEpoch, activeUser)) {
|
|
85
|
+
logger.warn(
|
|
86
|
+
`[mcp] Revoking an MCP service token issued before user ${activeUser.id}'s credentials changed`
|
|
87
|
+
);
|
|
88
|
+
await McpServiceToken.updateOne(
|
|
89
|
+
{_id: serviceToken._id, revokedAt: {$exists: false}},
|
|
90
|
+
{$set: {revokedAt: DateTime.now().toJSDate()}}
|
|
91
|
+
);
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
void McpServiceToken.updateOne(
|
|
95
|
+
{_id: serviceToken._id},
|
|
96
|
+
{$set: {lastUsedAt: DateTime.now().toJSDate()}}
|
|
97
|
+
).catch((error) => {
|
|
98
|
+
logger.debug(`MCP service token last-used update failed: ${error}`);
|
|
99
|
+
});
|
|
100
|
+
return {credential: "mcp-service-token", user: activeUser};
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
const authenticateOAuthAccessToken = async (
|
|
104
|
+
token: string,
|
|
105
|
+
userModel: UserModel
|
|
106
|
+
): Promise<MCPAuthResult | undefined> => {
|
|
107
|
+
const accessToken = await McpOAuthToken.verifyAccessToken(token);
|
|
108
|
+
if (!accessToken) {
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
const user = await userModel.findById(accessToken.userId);
|
|
112
|
+
const activeUser = rejectIfDisabled(user as unknown as User | undefined, "MCP OAuth");
|
|
113
|
+
if (!activeUser) {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
if (isCredentialEpochStale(accessToken.tokenEpoch, activeUser)) {
|
|
117
|
+
logger.warn(
|
|
118
|
+
`[mcp] Revoking an MCP OAuth grant issued before user ${activeUser.id}'s credentials changed`
|
|
119
|
+
);
|
|
120
|
+
await McpOAuthToken.revokeFamily(accessToken.familyId);
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
const scopes = (accessToken.scope ?? "").split(" ").filter((scope) => scope.length > 0);
|
|
124
|
+
return {credential: "oauth", scopes, user: activeUser};
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Resolve the caller and the credential type from raw headers using whichever auth providers
|
|
129
|
+
* are configured, mirroring authenticateMiddleware behavior: `mcp_` service tokens and `mcpat_`
|
|
130
|
+
* OAuth access tokens first (each is a distinct credential type), then a Better Auth session,
|
|
131
|
+
* then a Terreno JWT.
|
|
132
|
+
*/
|
|
133
|
+
export const extractAuthFromHeaders = async (
|
|
134
|
+
headers: Record<string, string | string[] | undefined>,
|
|
135
|
+
context: MCPAuthContext
|
|
136
|
+
): Promise<MCPAuthResult | undefined> => {
|
|
137
|
+
const {userModel, betterAuth, mcpServiceTokens, mcpOAuth} = context;
|
|
138
|
+
const {authorization, token} = bearerFromHeaders(headers);
|
|
139
|
+
|
|
140
|
+
if (mcpServiceTokens && token?.startsWith(MCP_SERVICE_TOKEN_PREFIX)) {
|
|
141
|
+
return authenticateServiceToken(token, userModel);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
if (mcpOAuth && token?.startsWith(MCP_OAUTH_ACCESS_TOKEN_PREFIX)) {
|
|
145
|
+
return authenticateOAuthAccessToken(token, userModel);
|
|
67
146
|
}
|
|
68
147
|
|
|
69
|
-
// Try Better Auth first if configured.
|
|
70
148
|
if (betterAuth) {
|
|
71
149
|
try {
|
|
72
150
|
const session = await betterAuth.api.getSession({
|
|
@@ -79,7 +157,8 @@ export const extractUserFromHeaders = async (
|
|
|
79
157
|
// working whether or not the consumer's model has the findOneOrNone plugin applied.
|
|
80
158
|
const appUser = await findOneOrNoneFor(userModel, {betterAuthId: session.user.id});
|
|
81
159
|
if (appUser) {
|
|
82
|
-
|
|
160
|
+
const activeUser = rejectIfDisabled(appUser as unknown as User, "Better Auth");
|
|
161
|
+
return activeUser ? {credential: "better-auth-session", user: activeUser} : undefined;
|
|
83
162
|
}
|
|
84
163
|
}
|
|
85
164
|
} catch (error) {
|
|
@@ -87,12 +166,7 @@ export const extractUserFromHeaders = async (
|
|
|
87
166
|
}
|
|
88
167
|
}
|
|
89
168
|
|
|
90
|
-
|
|
91
|
-
if (!authorization) {
|
|
92
|
-
return undefined;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
if (!token) {
|
|
169
|
+
if (!authorization || !token) {
|
|
96
170
|
return undefined;
|
|
97
171
|
}
|
|
98
172
|
|
|
@@ -113,9 +187,22 @@ export const extractUserFromHeaders = async (
|
|
|
113
187
|
}
|
|
114
188
|
|
|
115
189
|
const user = await userModel.findById(userId);
|
|
116
|
-
|
|
190
|
+
const activeUser = rejectIfDisabled(user as unknown as User | undefined, "JWT");
|
|
191
|
+
return activeUser ? {credential: "jwt", user: activeUser} : undefined;
|
|
117
192
|
} catch (error) {
|
|
118
193
|
logger.debug(`MCP JWT verification failed: ${error}`);
|
|
119
194
|
return undefined;
|
|
120
195
|
}
|
|
121
196
|
};
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Extract user from raw headers using whichever auth provider is configured.
|
|
200
|
+
* Works with both JWT and Better Auth, mirroring authenticateMiddleware behavior.
|
|
201
|
+
* Use {@link extractAuthFromHeaders} when the credential type matters.
|
|
202
|
+
*/
|
|
203
|
+
export const extractUserFromHeaders = async (
|
|
204
|
+
headers: Record<string, string | string[] | undefined>,
|
|
205
|
+
context: MCPAuthContext
|
|
206
|
+
): Promise<User | undefined> => {
|
|
207
|
+
return (await extractAuthFromHeaders(headers, context))?.user;
|
|
208
|
+
};
|
|
@@ -14,9 +14,15 @@ import type {MCPRequest, MCPToolArgs} from "./types";
|
|
|
14
14
|
*/
|
|
15
15
|
export const createMCPRequest = ({
|
|
16
16
|
body = {},
|
|
17
|
+
params = {},
|
|
18
|
+
query = {},
|
|
17
19
|
user,
|
|
18
20
|
}: {
|
|
19
21
|
body?: MCPToolArgs;
|
|
22
|
+
/** Route params an action tool fills in, such as the instance action's `id`. */
|
|
23
|
+
params?: Record<string, string>;
|
|
24
|
+
/** Tool arguments of a GET action, which REST would read from the query string. */
|
|
25
|
+
query?: Record<string, unknown>;
|
|
20
26
|
user?: User;
|
|
21
27
|
}): express.Request => {
|
|
22
28
|
const request: MCPRequest = {
|
|
@@ -24,8 +30,8 @@ export const createMCPRequest = ({
|
|
|
24
30
|
headers: {},
|
|
25
31
|
isMCPRequest: true,
|
|
26
32
|
method: "MCP",
|
|
27
|
-
params
|
|
28
|
-
query
|
|
33
|
+
params,
|
|
34
|
+
query,
|
|
29
35
|
user,
|
|
30
36
|
};
|
|
31
37
|
return request as unknown as express.Request;
|
package/src/mcp/handlers.test.ts
CHANGED
|
@@ -157,6 +157,33 @@ describe("MCP handlers", () => {
|
|
|
157
157
|
});
|
|
158
158
|
});
|
|
159
159
|
|
|
160
|
+
describe("list sort allowlist", () => {
|
|
161
|
+
it("rejects sorting on excluded or undeclared fields", async () => {
|
|
162
|
+
await NoteModel.create({ownerId: owner._id, secret: "b", title: "One"});
|
|
163
|
+
await NoteModel.create({ownerId: owner._id, secret: "a", title: "Two"});
|
|
164
|
+
const redacted: MCPRegistryEntry = {
|
|
165
|
+
...createEntry({queryFields: ["title", "secret"], sortFields: ["body"]}),
|
|
166
|
+
config: {...entry.config, excludeFields: ["secret"]},
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
assert.include(
|
|
170
|
+
errorText(await handleList(redacted, {sort: "secret"}, asUser(owner))),
|
|
171
|
+
"secret is not an allowed sort field"
|
|
172
|
+
);
|
|
173
|
+
assert.include(
|
|
174
|
+
errorText(await handleList(redacted, {sort: "title -ownerId"}, asUser(owner))),
|
|
175
|
+
"ownerId is not an allowed sort field"
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
const byTitle = await handleList(redacted, {sort: "-title"}, asUser(owner));
|
|
179
|
+
assert.notEqual(byTitle.isError, true);
|
|
180
|
+
const titles = (parseResult(byTitle).data as Array<{title: string}>).map((d) => d.title);
|
|
181
|
+
assert.deepEqual(titles, ["Two", "One"]);
|
|
182
|
+
const byBody = await handleList(redacted, {sort: "body"}, asUser(owner));
|
|
183
|
+
assert.notEqual(byBody.isError, true);
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
160
187
|
describe("queryFilter", () => {
|
|
161
188
|
it("returns an empty page when queryFilter resolves to null", async () => {
|
|
162
189
|
await NoteModel.create({ownerId: owner._id, title: "Hidden"});
|