@devries-cameron20 / t3code Mirror · read-only / commits / a8a32bbdf4
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 08:15 UTC

fix(server): accept case-insensitive MCP bearer schemes (#23782)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com>

Rishit committed Nov 2, 2026 at 02:24 UTC a8a32bbdf4070cf08c1b6759003ac8cbe51864aa
5 files changed +150 -26
apps/server/src/auth/EnvironmentAuth.test.ts
+22 -13
@@ -188,7 +188,13 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
188 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
189 const token = "reusable-dev-auth-token-that-is-long-enough";
190 const devExchange = yield* serverAuth.createBrowserSession(token, requestMetadata);
191 - for (const authorization of ["Bearer invalid", ""] as const) {
191 + for (const authorization of [
192 + "Bearer invalid",
193 + "bearer invalid",
194 + "bEaReR invalid",
195 + "Basic invalid",
196 + "",
197 + ] as const) {
198 const request = {
199 cookies: { [devExchange.cookieName ?? "missing"]: devExchange.sessionToken },
200 headers: { authorization },
@@ -671,24 +677,27 @@ it.layer(NodeServices.layer)("EnvironmentAuth.layer", (it) => {
677 }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web" }))),
678 );
679
674 - it.effect("keeps bearer socket upgrades independent of the page origin", () =>
675 - Effect.gen(function* () {
676 - const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
677 - const bearer = yield* serverAuth.issueSession();
678 - const verified = yield* serverAuth.authenticateWebSocketUpgrade(
679 - {
680 + it.effect.each(["Bearer", "bearer", "bEaReR"])(
681 + "accepts %s for HTTP and socket upgrades regardless of page origin",
682 + (scheme) =>
683 + Effect.gen(function* () {
684 + const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
685 + const bearer = yield* serverAuth.issueSession();
686 + const request = {
687 url: "/ws",
688 cookies: {},
689 headers: {
690 host: "192.168.1.50:3773",
691 origin: "http://192.168.1.50:8080",
685 - authorization: `Bearer ${bearer.token}`,
692 + authorization: `${scheme} ${bearer.token}`,
693 },
687 - } as never,
688 - "rpc",
689 - );
690 - expect(verified.sessionId).toBe(bearer.sessionId);
691 - }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
694 + } as never;
695 + const verified = yield* serverAuth.authenticateWebSocketUpgrade(request, "rpc");
696 + expect(verified.sessionId).toBe(bearer.sessionId);
697 + expect((yield* serverAuth.authenticateHttpRequest(request)).sessionId).toBe(
698 + bearer.sessionId,
699 + );
700 + }).pipe(Effect.provide(layerEnvironmentAuth({ mode: "web", host: "192.168.1.50" }))),
701 );
702
703 it.effect("binds a DPoP session's RPC socket ticket to its proof key", () =>
apps/server/src/auth/EnvironmentAuth.ts
+2 -2
@@ -628,9 +628,9 @@ const mapSessionVerificationErrors = <A, R>(
628 ),
629 );
630
631 -function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
631 +export function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
632 const header = request.headers["authorization"];
633 - if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
633 + if (typeof header !== "string" || !/^Bearer /i.test(header)) {
634 return null;
635 }
636 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
apps/server/src/auth/McpOAuth.test.ts
+8 -6
@@ -295,12 +295,14 @@ it.live("signs in with a pairing code and issues a token only /mcp accepts", ()
295
296 expect((yield* exchange(verifier)).status).toBe(400);
297
298 - const client = yield* auth.authenticateMcpClient(
299 - HttpServerRequest.fromWeb(
300 - at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
301 - ),
302 - );
303 - expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
298 + for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
299 + const client = yield* auth.authenticateMcpClient(
300 + HttpServerRequest.fromWeb(
301 + at("/mcp", { headers: { authorization: `${scheme} ${token.access_token}` } }),
302 + ),
303 + );
304 + expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
305 + }
306
307 const session = yield* handler(
308 at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }),
apps/server/src/mcp/McpHttpServer.test.ts
+108
@@ -20,12 +20,20 @@ import * as Context from "effect/Context";
20 import * as Deferred from "effect/Deferred";
21 import * as Effect from "effect/Effect";
22 import * as Layer from "effect/Layer";
23 +import * as Logger from "effect/Logger";
24 import * as Schema from "effect/Schema";
25 import * as Stream from "effect/Stream";
26 import { McpSchema, McpServer, Tool, Toolkit } from "effect/ai";
27 import { HttpBody, HttpClient, HttpClientRequest, HttpRouter } from "effect/http";
28
29 import * as ProjectService from "../project/ProjectService.ts";
30 +import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
31 +import * as McpOAuth from "../auth/McpOAuth.ts";
32 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
33 +import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
34 +import * as Sqlite from "../persistence/Sqlite.ts";
35 +import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36 +
37 import * as DeviceService from "../device/DeviceService.ts";
38 import * as PullRequestReviewGuideService from "../pullRequest/PullRequestReviewGuideService.ts";
39 import * as ServerConfig from "../config.ts";
@@ -946,6 +954,106 @@ it.effect("admits provider and OAuth client credentials and points only clients
954 ).pipe(Effect.provide(NodeHttpServer.layerTest)),
955 );
956
957 +it.effect("accepts case-insensitive MCP bearer schemes and diagnoses rejected credentials", () => {
958 + const messages: Array<unknown> = [];
959 + const logger = Logger.make(({ message }) => messages.push(message));
960 + const layerAuth = Layer.mergeAll(EnvironmentAuth.layer, McpSessionRegistry.layer).pipe(
961 + Layer.provideMerge(
962 + Layer.mock(ServerEnvironment.ServerEnvironment)({
963 + getEnvironmentId: Effect.succeed(environmentId),
964 + }),
965 + ),
966 + Layer.provideMerge(Sqlite.layerMemory),
967 + Layer.provide(ServerSecretStore.layer),
968 + Layer.provide(ManagedPolicy.layerTest()),
969 + Layer.provideMerge(ServerEnvironment.layerIdentity),
970 + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-auth-header-test-" })),
971 + Layer.provideMerge(NodeServices.layer),
972 + );
973 + return Effect.scoped(
974 + Effect.gen(function* () {
975 + const auth = yield* EnvironmentAuth.EnvironmentAuth;
976 + const registry = yield* McpSessionRegistry.McpSessionRegistry;
977 + const issued = yield* registry.issue({
978 + threadId,
979 + providerInstanceId: ProviderInstanceId.make("codex"),
980 + });
981 + const providerToken = issued.config.authorizationHeader.slice("Bearer ".length);
982 + const oauth = yield* auth.issueMcpClientSession({
983 + label: "MCP header test",
984 + access: "read-only",
985 + peerLink: false,
986 + client: { deviceType: "bot" },
987 + });
988 + yield* HttpRouter.serve(
989 + McpHttpServer.layerMcpTransport.pipe(
990 + Layer.provide(McpOAuth.layerMcpClientAuthenticator),
991 + Layer.provide(ServerSettings.layerTest()),
992 + ),
993 + { disableListenLog: true, disableLogger: true },
994 + ).pipe(Layer.build);
995 + const httpClient = yield* HttpClient.HttpClient;
996 + const initialize = (authorization?: string) =>
997 + httpClient.post("/mcp", {
998 + headers: {
999 + accept: "application/json, text/event-stream",
1000 + ...(authorization === undefined ? {} : { authorization }),
1001 + },
1002 + body: HttpBody.text(
1003 + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"mcp-header-test","version":"1.0.0"}}}`,
1004 + "application/json",
1005 + ),
1006 + });
1007 +
1008 + for (const scheme of ["Bearer", "bearer", "bEaReR"]) {
1009 + for (const [kind, token] of [
1010 + ["provider", providerToken],
1011 + ["OAuth", oauth.token],
1012 + ]) {
1013 + const response = yield* initialize(`${scheme} ${token}`);
1014 + expect.soft(response.status, `${kind} ${scheme}`).toBe(200);
1015 + }
1016 + }
1017 + messages.length = 0;
1018 + for (const [authorization, reason] of [
1019 + [undefined, "missing_authorization_header"],
1020 + [`Basic ${providerToken}`, "unsupported_scheme"],
1021 + ["Bearer", "missing_bearer_token"],
1022 + ["bEaReR ", "missing_bearer_token"],
1023 + [`bearer ${providerToken.toUpperCase()}`, "unknown_or_expired_token"],
1024 + [`bEaReR ${oauth.token.toUpperCase()}`, "unknown_or_expired_token"],
1025 + ] as const) {
1026 + const response = yield* initialize(authorization);
1027 + expect(response.status).toBe(401);
1028 + expect
1029 + .soft(messages.at(-1))
1030 + .toEqual(["rejected MCP request with an unusable credential", { reason }]);
1031 + const body = yield* response.text;
1032 + expect(body).not.toContain(providerToken);
1033 + expect(body).not.toContain(oauth.token);
1034 + expect(JSON.stringify(response.headers)).not.toContain(providerToken);
1035 + expect(JSON.stringify(response.headers)).not.toContain(oauth.token);
1036 + }
1037 + yield* registry.revokeThread(threadId);
1038 + yield* auth.revokeSession(oauth.sessionId);
1039 + for (const token of [providerToken, oauth.token]) {
1040 + expect((yield* initialize(`bearer ${token}`)).status).toBe(401);
1041 + }
1042 + expect(JSON.stringify(messages)).not.toContain(providerToken);
1043 + expect(JSON.stringify(messages)).not.toContain(oauth.token);
1044 + expect(JSON.stringify(messages)).not.toContain(providerToken.toUpperCase());
1045 + expect(JSON.stringify(messages)).not.toContain(oauth.token.toUpperCase());
1046 + }),
1047 + ).pipe(
1048 + Effect.provide(
1049 + layerAuth.pipe(
1050 + Layer.provideMerge(NodeHttpServer.layerTest),
1051 + Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
1052 + ),
1053 + ),
1054 + );
1055 +});
1056 +
1057 it.effect("hides tools for links and refuses another environment while the beta is off", () =>
1058 Effect.scoped(
1059 Effect.gen(function* () {
apps/server/src/mcp/McpHttpServer.ts
+10 -5
@@ -24,6 +24,7 @@ import {
24 } from "@t3tools/contracts";
25
26 import packageJson from "../../package.json" with { type: "json" };
27 +import { parseBearerToken } from "../auth/EnvironmentAuth.ts";
28 import * as ServerConfig from "../config.ts";
29 import * as ServerSettings from "../serverSettings.ts";
30 import * as DeviceService from "../device/DeviceService.ts";
@@ -204,10 +205,7 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
205 return Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
206 const request = yield* HttpServerRequest.HttpServerRequest;
207 const authorization = request.headers.authorization;
207 - const token =
208 - authorization?.startsWith("Bearer ") === true
209 - ? authorization.slice("Bearer ".length).trim()
210 - : "";
208 + const token = parseBearerToken(request) ?? "";
209 const invocation =
210 (yield* registry.resolve(token)) ??
211 (Option.isSome(clients) && token.length > 0
@@ -215,7 +213,14 @@ const makeMcpAuthMiddleware = Effect.gen(function* () {
213 : undefined);
214 if (!invocation) {
215 yield* Effect.logWarning("rejected MCP request with an unusable credential", {
218 - reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
216 + reason:
217 + authorization === undefined
218 + ? "missing_authorization_header"
219 + : authorization.split(" ", 1)[0]?.toLowerCase() !== "bearer"
220 + ? "unsupported_scheme"
221 + : token.length === 0
222 + ? "missing_bearer_token"
223 + : "unknown_or_expired_token",
224 });
225 return unauthorized({
226 request,