-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathmcp-http.request.ts
More file actions
186 lines (168 loc) · 6.57 KB
/
Copy pathmcp-http.request.ts
File metadata and controls
186 lines (168 loc) · 6.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import type { IncomingMessage, ServerResponse } from "node:http";
import type { InboundTurnKind } from "../channels/turn/kind.js";
import { resolveMainSessionKey } from "../config/sessions.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { isTruthyEnvValue } from "../infra/env.js";
import { safeEqualSecret } from "../security/secret-equal.js";
import { normalizeOptionalString } from "../shared/string-coerce.js";
import { normalizeMessageChannel } from "../utils/message-channel.js";
import { getHeader } from "./http-utils.js";
import { isLoopbackAddress } from "./net.js";
import { checkBrowserOrigin } from "./origin-check.js";
const MAX_MCP_BODY_BYTES = 1_048_576;
function shouldLogMcpLoopbackHttp(): boolean {
return (
isTruthyEnvValue(process.env.OPENCLAW_CLI_BACKEND_LOG_OUTPUT) ||
isTruthyEnvValue(process.env.OPENCLAW_LIVE_CLI_BACKEND_DEBUG)
);
}
function logMcpLoopbackHttp(step: string, details: Record<string, unknown>): void {
if (!shouldLogMcpLoopbackHttp()) {
return;
}
console.error(`[mcp-loopback] ${step} ${JSON.stringify(details)}`);
}
type McpRequestContext = {
sessionKey: string;
messageProvider: string | undefined;
accountId: string | undefined;
inboundTurnKind: InboundTurnKind | undefined;
senderIsOwner: boolean;
};
function resolveScopedSessionKey(cfg: OpenClawConfig, rawSessionKey: string | undefined): string {
const trimmed = normalizeOptionalString(rawSessionKey);
return !trimmed || trimmed === "main" ? resolveMainSessionKey(cfg) : trimmed;
}
function normalizeMcpInboundTurnKind(value: string | undefined): InboundTurnKind | undefined {
const trimmed = normalizeOptionalString(value);
return trimmed === "room_event" || trimmed === "user_request" ? trimmed : undefined;
}
function rejectsBrowserLoopbackRequest(req: IncomingMessage): boolean {
const origin = getHeader(req, "origin");
if (!origin) {
// No Origin header → not a browser request. Native MCP clients
// (curl, codex CLI, scripted MCP clients) never set Origin; let
// them through to the bearer check.
return false;
}
// Defer to checkBrowserOrigin. It already treats loopback peers
// talking to a loopback Origin as `local-loopback`, which covers
// the legitimate `localhost`↔`127.0.0.1` mismatch that browsers
// flag as `Sec-Fetch-Site: cross-site` even though both ends are
// local. A blanket cross-site early-return here would block that
// flow even with a valid bearer; the helper's isLocalClient +
// isLoopbackHost gating is the authoritative check.
return !checkBrowserOrigin({
requestHost: getHeader(req, "host"),
origin,
isLocalClient: isLoopbackAddress(req.socket?.remoteAddress),
}).ok;
}
export function validateMcpLoopbackRequest(params: {
req: IncomingMessage;
res: ServerResponse;
ownerToken: string;
nonOwnerToken: string;
}): { senderIsOwner: boolean } | null {
let url: URL;
try {
url = new URL(params.req.url ?? "/", `http://${params.req.headers.host ?? "localhost"}`);
} catch {
logMcpLoopbackHttp("reject", { reason: "bad_request_url", method: params.req.method ?? "" });
params.res.writeHead(400, { "Content-Type": "application/json" });
params.res.end(JSON.stringify({ error: "bad_request" }));
return null;
}
if (params.req.method === "GET" && url.pathname.startsWith("/.well-known/")) {
params.res.writeHead(404);
params.res.end();
return null;
}
if (url.pathname !== "/mcp") {
logMcpLoopbackHttp("reject", {
reason: "not_found",
method: params.req.method ?? "",
path: url.pathname,
});
params.res.writeHead(404, { "Content-Type": "application/json" });
params.res.end(JSON.stringify({ error: "not_found" }));
return null;
}
if (params.req.method !== "POST") {
logMcpLoopbackHttp("reject", {
reason: "method_not_allowed",
method: params.req.method ?? "",
path: url.pathname,
});
params.res.writeHead(405, { Allow: "POST" });
params.res.end();
return null;
}
if (rejectsBrowserLoopbackRequest(params.req)) {
logMcpLoopbackHttp("reject", {
reason: "forbidden_origin",
method: params.req.method ?? "",
origin: getHeader(params.req, "origin") ?? "",
});
params.res.writeHead(403, { "Content-Type": "application/json" });
params.res.end(JSON.stringify({ error: "forbidden" }));
return null;
}
const authHeader = getHeader(params.req, "authorization") ?? "";
const ownerTokenMatched = safeEqualSecret(authHeader, `Bearer ${params.ownerToken}`);
const nonOwnerTokenMatched = safeEqualSecret(authHeader, `Bearer ${params.nonOwnerToken}`);
const senderIsOwner = ownerTokenMatched ? true : nonOwnerTokenMatched ? false : null;
if (senderIsOwner === null) {
logMcpLoopbackHttp("reject", {
reason: "unauthorized",
method: params.req.method ?? "",
hasAuthorization: authHeader.length > 0,
});
params.res.writeHead(401, { "Content-Type": "application/json" });
params.res.end(JSON.stringify({ error: "unauthorized" }));
return null;
}
const contentType = getHeader(params.req, "content-type") ?? "";
if (!contentType.startsWith("application/json")) {
logMcpLoopbackHttp("reject", {
reason: "unsupported_media_type",
method: params.req.method ?? "",
contentType,
});
params.res.writeHead(415, { "Content-Type": "application/json" });
params.res.end(JSON.stringify({ error: "unsupported_media_type" }));
return null;
}
return { senderIsOwner };
}
export async function readMcpHttpBody(req: IncomingMessage): Promise<string> {
return await new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let received = 0;
req.on("data", (chunk: Buffer) => {
received += chunk.length;
if (received > MAX_MCP_BODY_BYTES) {
req.destroy();
reject(new Error(`Request body exceeds ${MAX_MCP_BODY_BYTES} bytes`));
return;
}
chunks.push(chunk);
});
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
req.on("error", reject);
});
}
export function resolveMcpRequestContext(
req: IncomingMessage,
cfg: OpenClawConfig,
auth: { senderIsOwner: boolean },
): McpRequestContext {
return {
sessionKey: resolveScopedSessionKey(cfg, getHeader(req, "x-session-key")),
messageProvider:
normalizeMessageChannel(getHeader(req, "x-openclaw-message-channel")) ?? undefined,
accountId: normalizeOptionalString(getHeader(req, "x-openclaw-account-id")),
inboundTurnKind: normalizeMcpInboundTurnKind(getHeader(req, "x-openclaw-inbound-turn-kind")),
senderIsOwner: auth.senderIsOwner,
};
}