keryx 0.39.1 → 0.40.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/classes/Action.ts +9 -3
- package/initializers/actionts.ts +6 -1
- package/initializers/mcp.ts +37 -2
- package/initializers/pubsub.ts +4 -2
- package/package.json +1 -1
- package/util/http.ts +8 -1
- package/util/mcpAppBundler.ts +29 -2
- package/util/mcpServer.ts +71 -1
- package/util/webResponse.ts +8 -2
package/classes/Action.ts
CHANGED
|
@@ -91,7 +91,11 @@ export type OAuthActionResponse = {
|
|
|
91
91
|
};
|
|
92
92
|
|
|
93
93
|
export type McpActionConfig = {
|
|
94
|
-
/**
|
|
94
|
+
/**
|
|
95
|
+
* Expose this action as an MCP tool. Tools are **opt-in** (default `false`):
|
|
96
|
+
* set `tool: true` to publish the action to MCP clients. Declaring an MCP App
|
|
97
|
+
* via `ui` implies a tool unless `tool` is explicitly `false`.
|
|
98
|
+
*/
|
|
95
99
|
tool?: boolean;
|
|
96
100
|
/** Tag as the OAuth login action */
|
|
97
101
|
isLoginAction?: boolean;
|
|
@@ -147,7 +151,7 @@ export type ActionConstructorInputs = {
|
|
|
147
151
|
/** Middleware hooks to run before/after `run()` */
|
|
148
152
|
middleware?: ActionMiddleware[];
|
|
149
153
|
|
|
150
|
-
/** Expose this action via the MCP server
|
|
154
|
+
/** Expose this action via the MCP server. Tools are opt-in — set `mcp: { tool: true }` to publish one. */
|
|
151
155
|
mcp?: McpActionConfig;
|
|
152
156
|
|
|
153
157
|
/** Expose this action via HTTP (defaults: route `/${name}`, method `GET`) */
|
|
@@ -234,7 +238,9 @@ export abstract class Action {
|
|
|
234
238
|
this.inputs = args.inputs;
|
|
235
239
|
this.middleware = args.middleware ?? [];
|
|
236
240
|
this.timeout = args.timeout;
|
|
237
|
-
|
|
241
|
+
// MCP tools are opt-in — see the actions initializer for rationale. An action
|
|
242
|
+
// becomes a tool only when it sets `mcp.tool = true` (or declares `mcp.ui`).
|
|
243
|
+
this.mcp = { tool: false, ...args.mcp };
|
|
238
244
|
this.web = {
|
|
239
245
|
route: args.web?.route ?? `/${this.name}`,
|
|
240
246
|
method: args.web?.method ?? HTTP_METHOD.GET,
|
package/initializers/actionts.ts
CHANGED
|
@@ -716,7 +716,12 @@ export class Actions extends Initializer {
|
|
|
716
716
|
|
|
717
717
|
for (const a of actions) {
|
|
718
718
|
if (!a.description) a.description = `An Action: ${a.name}`;
|
|
719
|
-
|
|
719
|
+
// MCP tools are opt-in: an action is exposed as a tool only when it
|
|
720
|
+
// explicitly sets `mcp.tool = true` (or declares an MCP App via `mcp.ui`).
|
|
721
|
+
// Defaulting to `false` prevents actions — especially destructive or
|
|
722
|
+
// maintenance ones — from being silently reachable by any authenticated
|
|
723
|
+
// MCP client just because they exist.
|
|
724
|
+
a.mcp = { tool: false, ...a.mcp };
|
|
720
725
|
}
|
|
721
726
|
|
|
722
727
|
logger.info(
|
package/initializers/mcp.ts
CHANGED
|
@@ -20,7 +20,9 @@ import {
|
|
|
20
20
|
forgetMcpSession,
|
|
21
21
|
formatToolName,
|
|
22
22
|
handleTransportRequest,
|
|
23
|
+
isMcpSessionAuthorizedForChannel,
|
|
23
24
|
type McpAuthInfo,
|
|
25
|
+
type McpSessionAuth,
|
|
24
26
|
mcpJsonResponse,
|
|
25
27
|
parseToolName,
|
|
26
28
|
readMcpSessionRecord,
|
|
@@ -85,11 +87,21 @@ declare module "keryx" {
|
|
|
85
87
|
export class McpInitializer extends Initializer {
|
|
86
88
|
constructor() {
|
|
87
89
|
super(namespace);
|
|
88
|
-
this.dependsOn = [
|
|
90
|
+
this.dependsOn = [
|
|
91
|
+
"hooks",
|
|
92
|
+
"actions",
|
|
93
|
+
"oauth",
|
|
94
|
+
"connections",
|
|
95
|
+
"pubsub",
|
|
96
|
+
"channels",
|
|
97
|
+
];
|
|
89
98
|
}
|
|
90
99
|
|
|
91
100
|
async initialize() {
|
|
92
101
|
const mcpServers: McpServer[] = [];
|
|
102
|
+
// Per-session auth context, so a broadcast is delivered only to sessions
|
|
103
|
+
// whose user is authorized for its channel (see sendNotification).
|
|
104
|
+
const mcpServerAuth = new Map<McpServer, McpSessionAuth>();
|
|
93
105
|
const transports = new Map<
|
|
94
106
|
string,
|
|
95
107
|
{
|
|
@@ -98,8 +110,21 @@ export class McpInitializer extends Initializer {
|
|
|
98
110
|
}
|
|
99
111
|
>();
|
|
100
112
|
|
|
101
|
-
|
|
113
|
+
// Deliver a PubSub broadcast to MCP sessions as a logging notification, but
|
|
114
|
+
// ONLY to sessions whose user is authorized to subscribe to the broadcast's
|
|
115
|
+
// channel. Without this gate every session on the node would receive every
|
|
116
|
+
// broadcast — a cross-user/cross-tenant data leak — because MCP sessions
|
|
117
|
+
// have no per-channel subscription of their own. Sessions with no captured
|
|
118
|
+
// auth context are skipped (fail closed).
|
|
119
|
+
async function sendNotification(payload: PubSubMessage) {
|
|
102
120
|
for (const server of mcpServers) {
|
|
121
|
+
const auth = mcpServerAuth.get(server);
|
|
122
|
+
if (!auth) continue;
|
|
123
|
+
const authorized = await isMcpSessionAuthorizedForChannel(
|
|
124
|
+
auth,
|
|
125
|
+
payload.channel,
|
|
126
|
+
);
|
|
127
|
+
if (!authorized) continue;
|
|
103
128
|
try {
|
|
104
129
|
server.server
|
|
105
130
|
.sendLoggingMessage({
|
|
@@ -121,6 +146,7 @@ export class McpInitializer extends Initializer {
|
|
|
121
146
|
|
|
122
147
|
return {
|
|
123
148
|
mcpServers,
|
|
149
|
+
mcpServerAuth,
|
|
124
150
|
transports,
|
|
125
151
|
handleRequest: null as McpHandleRequest | null,
|
|
126
152
|
sendNotification,
|
|
@@ -273,6 +299,13 @@ export class McpInitializer extends Initializer {
|
|
|
273
299
|
// New session — create a new McpServer + transport
|
|
274
300
|
const mcpServer = createMcpServer();
|
|
275
301
|
mcpServers.push(mcpServer);
|
|
302
|
+
// Capture the session's auth context so channel-broadcast delivery can
|
|
303
|
+
// authorize this session (see sendNotification).
|
|
304
|
+
api.mcp.mcpServerAuth.set(mcpServer, {
|
|
305
|
+
clientId: authInfo.clientId,
|
|
306
|
+
userId: authInfo.extra?.userId,
|
|
307
|
+
ip,
|
|
308
|
+
});
|
|
276
309
|
|
|
277
310
|
const sessionClientId = authInfo.clientId;
|
|
278
311
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
@@ -344,6 +377,7 @@ export class McpInitializer extends Initializer {
|
|
|
344
377
|
sessionId,
|
|
345
378
|
record.clientId,
|
|
346
379
|
record.protocolVersion,
|
|
380
|
+
{ userId: authInfo.extra?.userId, ip },
|
|
347
381
|
);
|
|
348
382
|
}
|
|
349
383
|
|
|
@@ -390,6 +424,7 @@ export class McpInitializer extends Initializer {
|
|
|
390
424
|
}
|
|
391
425
|
}
|
|
392
426
|
api.mcp.mcpServers.length = 0;
|
|
427
|
+
api.mcp.mcpServerAuth.clear();
|
|
393
428
|
|
|
394
429
|
api.mcp.handleRequest = null;
|
|
395
430
|
}
|
package/initializers/pubsub.ts
CHANGED
|
@@ -88,9 +88,11 @@ export class PubSub extends Initializer {
|
|
|
88
88
|
}
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
// Forward to MCP as notifications
|
|
91
|
+
// Forward to MCP as notifications (authorized per-session; fire-and-forget).
|
|
92
92
|
if (config.server.mcp.enabled && api.mcp?.sendNotification) {
|
|
93
|
-
api.mcp.sendNotification(payload)
|
|
93
|
+
void api.mcp.sendNotification(payload).catch(() => {
|
|
94
|
+
// notification delivery is best-effort
|
|
95
|
+
});
|
|
94
96
|
}
|
|
95
97
|
}
|
|
96
98
|
}
|
package/package.json
CHANGED
package/util/http.ts
CHANGED
|
@@ -65,7 +65,14 @@ export function buildCorsHeaders(
|
|
|
65
65
|
const headers: Record<string, string> = { ...extra };
|
|
66
66
|
const allowedOrigins = config.server.web.allowedOrigins;
|
|
67
67
|
|
|
68
|
-
if (allowedOrigins === "*"
|
|
68
|
+
if (allowedOrigins === "*") {
|
|
69
|
+
// Wildcard: always emit a literal "*" and never reflect the specific request
|
|
70
|
+
// origin. Reflecting the origin sets `Vary: Origin`, which downstream (see
|
|
71
|
+
// buildHeaders in webResponse.ts) adds `Access-Control-Allow-Credentials:
|
|
72
|
+
// true` — and reflecting an *arbitrary* origin together with credentials lets
|
|
73
|
+
// any website read a victim's authenticated cross-origin responses. A literal
|
|
74
|
+
// "*" can never carry credentials (browsers forbid the combination), so this
|
|
75
|
+
// stays a safe permissive default for public, non-credentialed endpoints.
|
|
69
76
|
headers["Access-Control-Allow-Origin"] = "*";
|
|
70
77
|
} else if (
|
|
71
78
|
requestOrigin &&
|
package/util/mcpAppBundler.ts
CHANGED
|
@@ -35,6 +35,30 @@ const COMMENT_PLACEHOLDER = "/* MCP_APP_CLIENT */";
|
|
|
35
35
|
const THEME_PLACEHOLDER = "/* MCP_APP_THEME */";
|
|
36
36
|
/** Matches an empty `<script type="module">` tag (the preferred, declarative injection point). */
|
|
37
37
|
const EMPTY_MODULE_SCRIPT = /<script\s+type=["']module["']>\s*<\/script>/;
|
|
38
|
+
/**
|
|
39
|
+
* Matches the sequences that let bundled JS prematurely terminate (or corrupt) the inline
|
|
40
|
+
* `<script>` element it is embedded in: a closing `</script` tag (case-insensitive) and an
|
|
41
|
+
* `<!--` comment opener (which flips the HTML parser into "script data escaped" state).
|
|
42
|
+
*/
|
|
43
|
+
const SCRIPT_BREAKOUT = /<(\/script|!--)/gi;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Make bundled JS safe to inline inside an HTML `<script>` element. HTML parsers end a
|
|
47
|
+
* script at the first literal `</script>` (and `<!--` can start an escaped state that hides
|
|
48
|
+
* a later real `</script>`), so an unescaped bundle terminates the tag early and the rest
|
|
49
|
+
* renders as page text. Backslash-escaping the `<` neutralizes both without changing JS
|
|
50
|
+
* semantics: `<\/script` is identical to `</script` in every JS context, and `<\!--` is an
|
|
51
|
+
* identity escape inside the string literals where `<!--` appears in minified bundles.
|
|
52
|
+
*
|
|
53
|
+
* @param script - The bundled client JS to embed.
|
|
54
|
+
* @returns The JS with `</script`/`<!--` sequences backslash-escaped.
|
|
55
|
+
*/
|
|
56
|
+
export function escapeScriptForInlineHtml(script: string): string {
|
|
57
|
+
return script.replace(
|
|
58
|
+
SCRIPT_BREAKOUT,
|
|
59
|
+
(_match, tail: string) => `<\\${tail}`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
38
62
|
|
|
39
63
|
/** Resolved HTML per UI action, computed once at boot by {@link resolveMcpAppUiResources}. */
|
|
40
64
|
const resolvedUiHtml = new Map<Action, string>();
|
|
@@ -67,9 +91,12 @@ export async function bundleMcpAppClient(
|
|
|
67
91
|
* `<script type="module"></script>`, then a `MCP_APP_CLIENT` placeholder comment,
|
|
68
92
|
* then just before `</body>`, and finally appends as a last resort.
|
|
69
93
|
*
|
|
70
|
-
*
|
|
94
|
+
* The bundle is HTML-escaped ({@link escapeScriptForInlineHtml}) first so `</script>`
|
|
95
|
+
* sequences inside the JS cannot close the module tag early. Uses replacer functions so
|
|
96
|
+
* `$`-sequences in the bundled JS are inserted literally.
|
|
71
97
|
*/
|
|
72
|
-
function injectClientScript(shell: string,
|
|
98
|
+
function injectClientScript(shell: string, rawScript: string): string {
|
|
99
|
+
const script = escapeScriptForInlineHtml(rawScript);
|
|
73
100
|
if (EMPTY_MODULE_SCRIPT.test(shell)) {
|
|
74
101
|
return shell.replace(
|
|
75
102
|
EMPTY_MODULE_SCRIPT,
|
package/util/mcpServer.ts
CHANGED
|
@@ -79,6 +79,61 @@ export async function createMcpConnection(extra: {
|
|
|
79
79
|
return connection;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* Auth context captured for a live MCP session (`McpServer`), used to authorize
|
|
84
|
+
* which channel broadcasts that session is allowed to receive. Keyed by
|
|
85
|
+
* `McpServer` in `api.mcp.mcpServerAuth`.
|
|
86
|
+
*/
|
|
87
|
+
export type McpSessionAuth = {
|
|
88
|
+
/** OAuth client id that owns the session. */
|
|
89
|
+
clientId: string;
|
|
90
|
+
/** Authenticated user id from the session's access token, if any. */
|
|
91
|
+
userId?: unknown;
|
|
92
|
+
/** Remote IP captured at session creation (best-effort). */
|
|
93
|
+
ip?: string;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Decide whether an MCP session's user is allowed to receive broadcasts for a
|
|
98
|
+
* channel. Runs the channel's real subscription authorization
|
|
99
|
+
* ({@link api.channels.authorizeSubscription}) against a throwaway in-memory
|
|
100
|
+
* probe connection so app-defined channel middleware/`authorize()` rules apply
|
|
101
|
+
* exactly as they do for WebSocket subscribers.
|
|
102
|
+
*
|
|
103
|
+
* The probe's session is populated in memory (never persisted to Redis) so this
|
|
104
|
+
* check adds no session writes on the broadcast hot path. Fails closed: returns
|
|
105
|
+
* `false` on any authorization error or unknown channel.
|
|
106
|
+
*
|
|
107
|
+
* @param auth - The session's captured auth context.
|
|
108
|
+
* @param channelName - The channel the broadcast targets.
|
|
109
|
+
* @returns `true` only if the session's user may subscribe to `channelName`.
|
|
110
|
+
*/
|
|
111
|
+
export async function isMcpSessionAuthorizedForChannel(
|
|
112
|
+
auth: McpSessionAuth,
|
|
113
|
+
channelName: string,
|
|
114
|
+
): Promise<boolean> {
|
|
115
|
+
const probe = new Connection(
|
|
116
|
+
CONNECTION_TYPE.MCP,
|
|
117
|
+
auth.ip ?? "unknown",
|
|
118
|
+
randomUUID(),
|
|
119
|
+
);
|
|
120
|
+
probe.session = {
|
|
121
|
+
id: probe.sessionId,
|
|
122
|
+
cookieName: config.session.cookieName,
|
|
123
|
+
createdAt: new Date().getTime(),
|
|
124
|
+
data: auth.userId != null ? { userId: auth.userId } : {},
|
|
125
|
+
};
|
|
126
|
+
probe.sessionLoaded = true;
|
|
127
|
+
try {
|
|
128
|
+
await api.channels.authorizeSubscription(channelName, probe);
|
|
129
|
+
return true;
|
|
130
|
+
} catch {
|
|
131
|
+
return false;
|
|
132
|
+
} finally {
|
|
133
|
+
probe.destroy();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
82
137
|
/**
|
|
83
138
|
* Forward a request to an MCP transport and return the response with CORS headers.
|
|
84
139
|
* Handles the try/catch + error response pattern shared by new-session and existing-session paths.
|
|
@@ -222,6 +277,7 @@ export function forgetMcpSession(
|
|
|
222
277
|
if (sessionId) api.mcp.transports.delete(sessionId);
|
|
223
278
|
const idx = api.mcp.mcpServers.indexOf(mcpServer);
|
|
224
279
|
if (idx !== -1) api.mcp.mcpServers.splice(idx, 1);
|
|
280
|
+
api.mcp.mcpServerAuth.delete(mcpServer);
|
|
225
281
|
}
|
|
226
282
|
|
|
227
283
|
/**
|
|
@@ -312,12 +368,15 @@ const adoptionsInFlight = new Map<
|
|
|
312
368
|
* @param sessionId - The transport session id to adopt.
|
|
313
369
|
* @param clientId - The OAuth client id that owns the session (from the registry record).
|
|
314
370
|
* @param protocolVersion - The negotiated protocol version from the registry record, if any.
|
|
371
|
+
* @param auth - The adopting request's user id / ip, captured so channel-broadcast
|
|
372
|
+
* authorization ({@link isMcpSessionAuthorizedForChannel}) works for this session too.
|
|
315
373
|
* @returns The connected, initialized transport (also registered in `api.mcp.transports`).
|
|
316
374
|
*/
|
|
317
375
|
export async function adoptMcpSession(
|
|
318
376
|
sessionId: string,
|
|
319
377
|
clientId: string,
|
|
320
378
|
protocolVersion: string | undefined,
|
|
379
|
+
auth?: Pick<McpSessionAuth, "userId" | "ip">,
|
|
321
380
|
): Promise<WebStandardStreamableHTTPServerTransport> {
|
|
322
381
|
const inFlight = adoptionsInFlight.get(sessionId);
|
|
323
382
|
if (inFlight) return inFlight;
|
|
@@ -325,6 +384,11 @@ export async function adoptMcpSession(
|
|
|
325
384
|
const promise = (async () => {
|
|
326
385
|
const mcpServer = createMcpServer();
|
|
327
386
|
api.mcp.mcpServers.push(mcpServer);
|
|
387
|
+
api.mcp.mcpServerAuth.set(mcpServer, {
|
|
388
|
+
clientId,
|
|
389
|
+
userId: auth?.userId,
|
|
390
|
+
ip: auth?.ip,
|
|
391
|
+
});
|
|
328
392
|
try {
|
|
329
393
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
330
394
|
sessionIdGenerator: () => sessionId,
|
|
@@ -424,7 +488,13 @@ function buildUiMeta(ui: McpUiConfig): Record<string, unknown> {
|
|
|
424
488
|
function registerTools(mcpServer: McpServer) {
|
|
425
489
|
const registered = new Set<string>();
|
|
426
490
|
for (const action of api.actions.actions) {
|
|
427
|
-
|
|
491
|
+
// Tools are opt-in: register only actions that explicitly set `mcp.tool =
|
|
492
|
+
// true`, or that declare an MCP App (`mcp.ui`) without opting out. Every
|
|
493
|
+
// other action — including those with no `mcp` config — is never exposed.
|
|
494
|
+
const isTool =
|
|
495
|
+
action.mcp?.tool === true ||
|
|
496
|
+
(action.mcp?.ui != null && action.mcp?.tool !== false);
|
|
497
|
+
if (!isTool) continue;
|
|
428
498
|
|
|
429
499
|
const toolName = formatToolName(action.name);
|
|
430
500
|
if (registered.has(toolName)) continue;
|
package/util/webResponse.ts
CHANGED
|
@@ -29,8 +29,14 @@ export const buildHeaders = (
|
|
|
29
29
|
"Access-Control-Allow-Methods": config.server.web.allowedMethods,
|
|
30
30
|
"Access-Control-Allow-Headers": config.server.web.allowedHeaders,
|
|
31
31
|
});
|
|
32
|
-
|
|
33
|
-
|
|
32
|
+
// Only attach credentials for a specific, allow-listed origin — never for the
|
|
33
|
+
// wildcard "*". Browsers forbid combining "*" with credentials, and reflecting
|
|
34
|
+
// an arbitrary origin alongside credentials would let any site read a victim's
|
|
35
|
+
// authenticated responses (see buildCorsHeaders in util/http.ts).
|
|
36
|
+
if (
|
|
37
|
+
cors["Access-Control-Allow-Origin"] &&
|
|
38
|
+
cors["Access-Control-Allow-Origin"] !== "*"
|
|
39
|
+
) {
|
|
34
40
|
cors["Access-Control-Allow-Credentials"] = "true";
|
|
35
41
|
}
|
|
36
42
|
Object.assign(headers, cors);
|