feat(server): outside agents sign in to the T3 MCP server with OAuth (#16336)

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-06 14:09:35 -07:00
1 parent 2f85686d9d
commit 2c8be5893e
29 files changed
+2531 -67

No files matched your search

+161 -2
View File
@@ -2,6 +2,8 @@ import {
AuthAccessTokenType,
AuthAccessWriteScope,
AuthAdministrativeScopes,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
AuthStandardClientScopes,
type AuthAccessTokenResult,
type AuthBrowserSessionResult,
@@ -9,6 +11,7 @@ import {
type AuthClientSession,
type AuthCreatePairingCredentialInput,
type AuthEnvironmentScope,
type AuthMcpClientAccess,
type AuthPairingLink,
type AuthPairingCredentialResult,
type AuthSessionId,
@@ -63,6 +66,31 @@ export interface IssuedBearerSession {
readonly expiresAt: DateTime.Utc;
}
/**
* Sessions an MCP client (an agent T3 Code did not launch) obtains through
* OAuth. They are accepted only by `/mcp`, where every action is capped by the
* access the user approved; the HTTP API and WebSocket reject them so an agent
* token cannot reach the full RPC surface around that cap.
*
* A read-only grant holds `orchestration:read` alone. Any other grant also
* holds `orchestration:operate` and carries its runtime-mode ceiling.
*/
const MCP_CLIENT_SUBJECT = "mcp-client";
const MCP_CLIENT_SESSION_TTL = Duration.days(30);
export const mcpClientScopes = (
access: AuthMcpClientAccess,
): ReadonlyArray<AuthEnvironmentScope> =>
access === "read-only"
? [AuthOrchestrationReadScope]
: [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
export interface McpClientSession {
readonly sessionId: AuthSessionId;
readonly label: string;
readonly access: AuthMcpClientAccess;
}
export interface AuthenticatedSession {
readonly sessionId: AuthSessionId;
readonly subject: string;
@@ -406,6 +434,19 @@ export const serverAuthInvalidRequestReason = (
): "invalid_scope" | "scope_not_granted" =>
error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
export class ServerAuthMcpApprovalCodeError extends Schema.TaggedError<ServerAuthMcpApprovalCodeError>()(
"ServerAuthMcpApprovalCodeError",
{ reason: Schema.Literals(["unknown_or_used", "not_a_pairing_code", "insufficient_scope"]) },
) {
override get message(): string {
return this.reason === "insufficient_scope"
? "That pairing code cannot grant this access, and it is now used up. Create one with the standard scopes, or choose Read only with a new code."
: this.reason === "not_a_pairing_code"
? "That is not a one-time pairing code."
: "That pairing code is unknown, expired, or already used.";
}
}
export class ServerAuthForbiddenOperationError extends Schema.TaggedError<ServerAuthForbiddenOperationError>()(
"ServerAuthForbiddenOperationError",
{},
@@ -502,6 +543,32 @@ export class EnvironmentAuth extends Context.Service<
readonly issueStartupPairingUrl: (
baseUrl: string,
) => Effect.Effect<string, ServerAuthInternalError>;
/** Only bearer `mcp-client` sessions; never cookies or proof-bound tokens. */
readonly authenticateMcpClient: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<McpClientSession, ServerAuthCredentialError | ServerAuthInternalError>;
readonly issueMcpClientSession: (input: {
readonly label: string;
readonly access: AuthMcpClientAccess;
readonly client: AuthClientMetadata;
}) => Effect.Effect<
{ readonly token: string; readonly expiresAt: DateTime.DateTime },
ServerAuthInternalError
>;
/**
* Spends a one-time pairing code as approval for an MCP client with the
* given access; the code must hold every scope that access grants.
* Proof-bound codes (T3 Connect) are refused without being spent, and
* desktop bootstrap grants never qualify.
*/
readonly consumeMcpApprovalCode: (
code: string,
access: AuthMcpClientAccess,
) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
/** A browser cookie session only; a bearer header never counts as one. */
readonly authenticateBrowserSession: (
request: HttpServerRequest.HttpServerRequest,
) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
}
>()("t3/auth/EnvironmentAuth") {}
@@ -540,6 +607,15 @@ export function toBootstrapExchangeError(
});
}
const rejectMcpClientAudience = <S extends { readonly subject: string }>(session: S) =>
session.subject === MCP_CLIENT_SUBJECT
? Effect.fail(
new ServerAuthInvalidCredentialError({
diagnostic: "MCP client sessions are only accepted by the MCP endpoint.",
}),
).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp.")))
: Effect.succeed(session);
const mapSessionVerificationErrors = <A, R>(
effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
@@ -624,6 +700,8 @@ export const make = Effect.gen(function* () {
)
: Effect.void,
),
mapSessionVerificationErrors,
Effect.flatMap(rejectMcpClientAudience),
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
@@ -632,7 +710,6 @@ export const make = Effect.gen(function* () {
...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
mapSessionVerificationErrors,
);
const authenticateRequest = (
@@ -1079,6 +1156,8 @@ export const make = Effect.gen(function* () {
const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
if (websocketTicket && websocketTicket.trim().length > 0) {
return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
mapSessionVerificationErrors,
Effect.flatMap(rejectMcpClientAudience),
Effect.map((session) => ({
sessionId: session.sessionId,
subject: session.subject,
@@ -1086,7 +1165,6 @@ export const make = Effect.gen(function* () {
scopes: session.scopes,
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
})),
mapSessionVerificationErrors,
);
}
}
@@ -1094,6 +1172,83 @@ export const make = Effect.gen(function* () {
return yield* authenticateRequest(request);
});
const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
const token = parseBearerToken(request);
if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
return sessions.verify(token).pipe(
mapSessionVerificationErrors,
Effect.flatMap((session) =>
session.subject === MCP_CLIENT_SUBJECT && session.method === "bearer-access-token"
? Effect.succeed({
sessionId: session.sessionId,
label: session.client.label ?? "MCP client",
access: session.scopes.includes(AuthOrchestrationOperateScope)
? (session.runtimeModeCeiling ?? "approval-required")
: "read-only",
} satisfies McpClientSession)
: Effect.fail(
new ServerAuthInvalidCredentialError({
diagnostic: "Only MCP client sessions are accepted here.",
}),
),
),
Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
);
};
const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
sessions
.issue({
subject: MCP_CLIENT_SUBJECT,
method: "bearer-access-token",
scopes: mcpClientScopes(input.access),
ttl: MCP_CLIENT_SESSION_TTL,
...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
client: { ...input.client, label: input.label, deviceType: "bot" },
})
.pipe(
Effect.map((issued) => ({ token: issued.token, expiresAt: issued.expiresAt })),
Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
);
const authenticateBrowserSession: EnvironmentAuth["Service"]["authenticateBrowserSession"] = (
request,
) => {
const token =
request.cookies[sessions.cookieName] ??
(sessions.legacyCookieName ? request.cookies[sessions.legacyCookieName] : undefined) ??
(devAuth ? request.cookies[devAuth.cookieName] : undefined);
if (!token) return Effect.fail(new ServerAuthMissingCredentialError({}));
return authenticateToken(token).pipe(
Effect.filterOrFail(
(session) => session.method === "browser-session-cookie" && !session.proofKeyThumbprint,
() => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),
),
Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),
);
};
const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
code,
access,
) =>
// No proof key: a code bound to a T3 Connect client's key fails without being spent.
resolveBootstrapGrant(code.trim()).pipe(
Effect.catchTags({
ServerAuthInvalidCredentialError: () =>
Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
}),
Effect.flatMap((grant) =>
grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
: mcpClientScopes(access).every((scope) => grant.scopes.includes(scope))
? Effect.void
: Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
),
Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
);
return EnvironmentAuth.of({
getDescriptor: () =>
Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
@@ -1116,6 +1271,10 @@ export const make = Effect.gen(function* () {
authenticateWebSocketUpgrade,
issueWebSocketTicket,
issueStartupPairingUrl,
authenticateMcpClient,
issueMcpClientSession,
consumeMcpApprovalCode,
authenticateBrowserSession,
});
});
+505
View File
@@ -0,0 +1,505 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
AuthAdministrativeScopes,
type AuthEnvironmentScope,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import { expect, it } from "@effect/vitest";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Etag from "effect/http/Etag";
import * as HttpPlatform from "effect/http/HttpPlatform";
import * as HttpRouter from "effect/http/HttpRouter";
import * as HttpServerRequest from "effect/http/HttpServerRequest";
import * as HttpApi from "effect/http-api/HttpApi";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as Schema from "effect/Schema";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as Sqlite from "../persistence/Sqlite.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as McpOAuth from "./McpOAuth.ts";
import * as McpOAuthHttp from "./mcpOAuthHttp.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import * as AuthHttp from "./http.ts";
class AuthTestApi extends HttpApi.make("environment")
.add(EnvironmentHttpApi.groups.auth)
.add(EnvironmentHttpApi.groups.mcpOAuth) {}
const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-oauth-test-" });
const layerEnvironmentAuth = EnvironmentAuth.layer.pipe(
Layer.provide(Sqlite.layerMemory),
Layer.provideMerge(ServerSecretStore.layer),
Layer.provideMerge(ServerEnvironment.layerIdentity),
Layer.provide(layerConfig),
);
// Each router gets its own database; the capture hands that router's EnvironmentAuth to its test.
const makeLayerRoutes = (capture: (auth: EnvironmentAuth.EnvironmentAuth["Service"]) => void) =>
Layer.mergeAll(
Layer.effectDiscard(
EnvironmentAuth.EnvironmentAuth.pipe(Effect.tap((auth) => Effect.sync(() => capture(auth)))),
),
HttpApiBuilder.layer(AuthTestApi).pipe(
Layer.provide(AuthHttp.layer),
Layer.provide(McpOAuthHttp.layer.pipe(Layer.provide(McpOAuth.layer))),
Layer.provide(AuthHttp.layerAuthenticatedAuth),
),
).pipe(
Layer.provideMerge(layerEnvironmentAuth),
Layer.provide(layerConfig),
Layer.provideMerge(
HttpPlatform.layer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(Etag.layerWeak),
),
),
Layer.provide(NodeServices.layer),
);
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
const ORIGIN = "https://box.example.ts.net";
const REDIRECT = "http://localhost/callback";
const verifier = "a".repeat(43) + "-verifier-for-tests";
/** base64url(SHA-256(verifier)), the S256 challenge for `verifier`. */
const challenge = "DeB41nTVkPwpbbYecrnqtVq7VXLezustdHAK4SWt13c";
/** Requests as they arrive behind an https proxy: plain http with the public Host. */
const at = (path: string, init?: RequestInit) =>
new Request(`http://127.0.0.1${path}`, {
...init,
headers: { host: "box.example.ts.net", "x-forwarded-proto": "https", ...init?.headers },
});
const form = (body: Record<string, string>) => ({
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(body).toString(),
});
type Handler = (request: Request) => Effect.Effect<Response>;
const withRoutes = <A, E>(
use: (handler: Handler, auth: EnvironmentAuth.EnvironmentAuth["Service"]) => Effect.Effect<A, E>,
) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const context = Context.make(Crypto.Crypto, crypto);
let routerAuth: EnvironmentAuth.EnvironmentAuth["Service"] | undefined;
const layerRoutes = makeLayerRoutes((auth) => {
routerAuth = auth;
});
return yield* Effect.acquireUseRelease(
Effect.sync(() => HttpRouter.toWebHandler(layerRoutes, { disableLogger: true })),
(web) =>
Effect.gen(function* () {
const handler: Handler = (request) => Effect.promise(() => web.handler(request, context));
// The router builds its layer on first request; a metadata read warms it.
yield* handler(at("/.well-known/oauth-authorization-server"));
return yield* use(handler, routerAuth!);
}),
(web) => Effect.promise(() => web.dispose()),
);
}).pipe(Effect.provide(NodeServices.layer));
const json = <A>(response: Response) => Effect.promise(() => response.json() as Promise<A>);
const postJson = (path: string, body: unknown, cookie?: string) =>
at(path, {
method: "POST",
headers: { "content-type": "application/json", ...(cookie ? { cookie } : {}) },
body: encodeJson(body),
});
/** What the approval page posts: the agent's request plus the user's choice. */
const decide = (
handler: Handler,
authorization: Record<string, string>,
decision: Record<string, string>,
cookie?: string,
) =>
handler(postJson("/oauth/mcp/decision", { authorization, decision }, cookie)).pipe(
Effect.flatMap((response) =>
json<{ redirectTo?: string; message?: string }>(response).pipe(
Effect.map((payload) => ({ status: response.status, ...payload })),
),
),
);
const register = (handler: Handler, redirect = REDIRECT) =>
handler(
at("/oauth/mcp/register", {
method: "POST",
headers: { "content-type": "application/json" },
body: encodeJson({
client_name: "Claude Code",
redirect_uris: [redirect],
grant_types: ["authorization_code", "refresh_token"],
token_endpoint_auth_method: "none",
}),
}),
);
const registeredClientId = (handler: Handler) =>
register(handler).pipe(
Effect.flatMap((response) => json<{ client_id: string }>(response)),
Effect.map((body) => body.client_id),
);
const authorizeParams = (clientId: string, redirect = "http://localhost:51234/callback") => ({
response_type: "code",
client_id: clientId,
redirect_uri: redirect,
code_challenge: challenge,
code_challenge_method: "S256",
state: "state-1",
resource: `${ORIGIN}/mcp`,
});
it.live("derives discovery metadata from the origin the client reached", () =>
withRoutes((handler) =>
Effect.gen(function* () {
const resource = yield* handler(at("/.well-known/oauth-protected-resource/mcp"));
expect(yield* json<unknown>(resource)).toMatchObject({
resource: `${ORIGIN}/mcp`,
authorization_servers: [ORIGIN],
});
const server = yield* json<unknown>(
yield* handler(at("/.well-known/oauth-authorization-server")),
);
expect(server).toMatchObject({
issuer: ORIGIN,
authorization_endpoint: `${ORIGIN}/oauth/mcp/authorize`,
token_endpoint: `${ORIGIN}/oauth/mcp/token`,
registration_endpoint: `${ORIGIN}/oauth/mcp/register`,
code_challenge_methods_supported: ["S256"],
});
}),
),
);
it.live("registers only loopback clients and never redirects for an unverified client", () =>
withRoutes((handler) =>
Effect.gen(function* () {
const remote = yield* register(handler, "https://attacker.example/callback");
expect(remote.status).toBe(400);
expect(yield* json<unknown>(remote)).toMatchObject({ error: "invalid_redirect_uri" });
const registered = yield* register(handler);
expect(registered.status).toBe(201);
const { client_id: clientId } = (yield* json<unknown>(registered)) as { client_id: string };
const forged = yield* handler(
at(
`/oauth/mcp/authorize?${new URLSearchParams(authorizeParams(`${clientId.split(".")[0]}.forged`))}`,
),
);
expect(forged.status).toBe(400);
expect(forged.headers.get("location")).toBeNull();
const unregistered = yield* handler(
at(
`/oauth/mcp/authorize?${new URLSearchParams(
authorizeParams(clientId, "http://localhost:51234/elsewhere"),
)}`,
),
);
expect(unregistered.status).toBe(400);
expect(unregistered.headers.get("location")).toBeNull();
// A valid request is handed to the web app's approval page, query intact.
const query = new URLSearchParams(authorizeParams(clientId)).toString();
const handoff = yield* handler(at(`/oauth/mcp/authorize?${query}`));
expect(handoff.status).toBe(302);
expect(handoff.headers.get("location")).toBe(`/connect-agent?${query}`);
const details = yield* handler(
postJson("/oauth/mcp/approval", authorizeParams(clientId)),
).pipe(Effect.flatMap(json<Record<string, unknown>>));
expect(details).toEqual({
clientName: "Claude Code",
redirectHost: "localhost:51234",
environmentHost: "box.example.ts.net",
});
// The approval endpoints re-check the request: a forged client gets a message, not a URL.
const forgedDetails = yield* handler(
postJson("/oauth/mcp/approval", authorizeParams(`${clientId.split(".")[0]}.forged`)),
);
expect(forgedDetails.status).toBe(400);
expect(yield* json<Record<string, unknown>>(forgedDetails)).not.toHaveProperty("redirectTo");
}),
),
);
it.live("signs in with a pairing code and issues a token only /mcp accepts", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const pairing = yield* auth.issuePairingCredential();
const params = authorizeParams(clientId);
const wrongCode = yield* decide(handler, params, {
_tag: "pairing-code",
access: "auto",
code: "nope",
});
expect(wrongCode.status).toBe(400);
expect(wrongCode.message).toContain("unknown, expired, or already used");
const approved = yield* decide(handler, params, {
_tag: "pairing-code",
access: "auto",
code: pairing.credential,
});
expect(approved.status).toBe(200);
const callback = new URL(approved.redirectTo!);
expect(callback.origin).toBe("http://localhost:51234");
expect(callback.searchParams.get("state")).toBe("state-1");
expect(callback.searchParams.get("iss")).toBe(ORIGIN);
const code = callback.searchParams.get("code")!;
const exchange = (codeVerifier: string) =>
handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: codeVerifier,
resource: `${ORIGIN}/mcp`,
}),
),
);
const tokenResponse = yield* exchange(verifier);
expect(tokenResponse.status).toBe(200);
const token = (yield* json<unknown>(tokenResponse)) as {
access_token: string;
scope: string;
};
expect(token.scope).toBe("orchestration:read orchestration:operate");
// Codes are single use.
expect((yield* exchange(verifier)).status).toBe(400);
const client = yield* auth.authenticateMcpClient(
HttpServerRequest.fromWeb(
at("/mcp", { headers: { authorization: `Bearer ${token.access_token}` } }),
),
);
expect(client).toMatchObject({ label: "Claude Code", access: "auto" });
// The same token is refused by the rest of the environment.
const session = yield* handler(
at("/api/auth/session", { headers: { authorization: `Bearer ${token.access_token}` } }),
);
expect(yield* json<unknown>(session)).toMatchObject({ authenticated: false });
const ticket = yield* handler(
at("/api/auth/websocket-ticket", {
method: "POST",
headers: { authorization: `Bearer ${token.access_token}` },
}),
);
expect(ticket.status).toBe(401);
}),
),
);
it.live("rejects a wrong PKCE verifier and spends the code", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const pairing = yield* auth.issuePairingCredential();
const params = authorizeParams(clientId);
const approved = yield* decide(handler, params, {
_tag: "pairing-code",
access: "approval-required",
code: pairing.credential,
});
const code = new URL(approved.redirectTo!).searchParams.get("code")!;
const exchange = (codeVerifier: string) =>
handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: codeVerifier,
}),
),
);
const wrong = yield* exchange("b".repeat(64));
expect(wrong.status).toBe(400);
expect(yield* json<unknown>(wrong)).toMatchObject({ error: "invalid_grant" });
expect((yield* exchange(verifier)).status).toBe(400);
}),
),
);
it.live(
"denies and refuses codes bound to another client's key or without the scopes it grants",
() =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const params = authorizeParams(clientId);
const denied = yield* decide(handler, params, { _tag: "deny" });
const deniedUrl = new URL(denied.redirectTo!);
expect(deniedUrl.searchParams.get("error")).toBe("access_denied");
expect(deniedUrl.searchParams.get("state")).toBe("state-1");
const approveWith = (code: string) =>
decide(handler, params, { _tag: "pairing-code", access: "auto", code });
// A T3 Connect code is bound to a device key: refused, and still usable by its device.
const bound = yield* auth.createPairingLink({
proofKeyThumbprint: "device-key-thumbprint",
});
expect((yield* approveWith(bound.credential)).status).toBe(400);
const stillValid = yield* auth
.exchangeBootstrapCredentialForAccessToken(
bound.credential,
undefined,
{ deviceType: "mobile" },
{ proofKeyThumbprint: "device-key-thumbprint" },
)
.pipe(
Effect.as(true),
Effect.orElseSucceed(() => false),
);
expect(stillValid).toBe(true);
const readOnly = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
const readOnlyResponse = yield* approveWith(readOnly.credential);
expect(readOnlyResponse.status).toBe(400);
expect(readOnlyResponse.message).toContain("cannot grant this access");
// A read-only code can approve read-only access.
const readOnlyCode = yield* auth.issuePairingCredential({ scopes: ["orchestration:read"] });
const readOnlyApproval = yield* decide(handler, params, {
_tag: "pairing-code",
access: "read-only",
code: readOnlyCode.credential,
});
expect(readOnlyApproval.status).toBe(200);
const readOnlyToken = yield* handler(
at(
"/oauth/mcp/token",
form({
grant_type: "authorization_code",
code: new URL(readOnlyApproval.redirectTo!).searchParams.get("code")!,
redirect_uri: params.redirect_uri,
client_id: clientId,
code_verifier: verifier,
resource: `${ORIGIN}/mcp`,
}),
),
).pipe(Effect.flatMap(json<{ access_token: string; scope: string }>));
expect(readOnlyToken.scope).toBe("orchestration:read");
const readOnlyClient = yield* auth.authenticateMcpClient(
HttpServerRequest.fromWeb(
at("/mcp", { headers: { authorization: `Bearer ${readOnlyToken.access_token}` } }),
),
);
expect(readOnlyClient.access).toBe("read-only");
}),
),
);
it.live("one-click approves only access the browser session holds the scopes for", () =>
withRoutes((handler, auth) =>
Effect.gen(function* () {
const clientId = yield* registeredClientId(handler);
const params = authorizeParams(clientId);
// Signs a browser in through the real route and returns its session cookie.
const browserCookie = (scopes: ReadonlyArray<AuthEnvironmentScope>) =>
Effect.gen(function* () {
const pairing = yield* auth.issuePairingCredential({ scopes });
const response = yield* handler(
at("/api/auth/browser-session", {
method: "POST",
headers: { "content-type": "application/json" },
body: encodeJson({ credential: pairing.credential }),
}),
);
return response.headers.getSetCookie()[0]!.split(";", 1)[0]!;
});
const details = (cookie: string) =>
handler(postJson("/oauth/mcp/approval", params, cookie)).pipe(
Effect.flatMap(json<{ csrfToken?: string; oneClickAccess?: ReadonlyArray<string> }>),
);
const admin = yield* browserCookie([...AuthAdministrativeScopes]);
const adminDetails = yield* details(admin);
expect(adminDetails.csrfToken).toEqual(expect.any(String));
expect(adminDetails.oneClickAccess).toEqual([
"read-only",
"approval-required",
"auto-accept-edits",
"auto",
"full-access",
]);
const oneClick = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "auto", csrfToken: adminDetails.csrfToken! },
admin,
);
expect(new URL(oneClick.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
// access:write alone cannot hand an agent thread control it does not hold.
const accessOnly = yield* browserCookie(["access:read", "access:write"]);
expect((yield* details(accessOnly)).csrfToken).toBeUndefined();
const forged = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "auto", csrfToken: "forged" },
accessOnly,
);
expect(forged.status).toBe(400);
expect(forged.message).toContain("Enter a pairing code instead");
// A session that can read but not operate threads may approve read-only access only.
const reader = yield* browserCookie(["access:write", "orchestration:read"]);
const readerDetails = yield* details(reader);
expect(readerDetails.csrfToken).toEqual(expect.any(String));
// The page shows the pairing-code field for anything above read only.
expect(readerDetails.oneClickAccess).toEqual(["read-only"]);
const tooBroad = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "auto", csrfToken: readerDetails.csrfToken! },
reader,
);
expect(tooBroad.status).toBe(400);
const readOnly = yield* decide(
handler,
params,
{ _tag: "browser-session", access: "read-only", csrfToken: readerDetails.csrfToken! },
reader,
);
expect(new URL(readOnly.redirectTo!).searchParams.get("code")).toEqual(expect.any(String));
}),
),
);
it("matches loopback redirects on everything but the port", () => {
expect(
McpOAuth.loopbackRedirectMatches("http://localhost/callback", "http://localhost:9/callback"),
).toBe(true);
expect(
McpOAuth.loopbackRedirectMatches("http://127.0.0.1:1/callback", "http://127.0.0.1:2/callback"),
).toBe(true);
expect(
McpOAuth.loopbackRedirectMatches("http://localhost/callback", "http://127.0.0.1/callback"),
).toBe(false);
expect(
McpOAuth.loopbackRedirectMatches("http://localhost/callback", "https://localhost/callback"),
).toBe(false);
});
+603
View File
@@ -0,0 +1,603 @@
import {
AuthAccessWriteScope,
type AuthMcpApprovalDecision,
type AuthMcpAuthorizationRequest,
type AuthMcpAuthorizationServerMetadata,
type AuthMcpClientRegistration,
type AuthMcpProtectedResourceMetadata,
AuthMcpRegistrationError,
AuthMcpTokenError,
type AuthMcpTokenRequest,
type AuthMcpTokenResult,
type AuthMcpClientAccess,
type AuthEnvironmentScope,
AuthOrchestrationOperateScope,
AuthOrchestrationReadScope,
} from "@t3tools/contracts";
import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import { HttpServerRequest } from "effect/http";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as McpHttpServer from "../mcp/McpHttpServer.ts";
import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as ServerSecretStore from "./ServerSecretStore.ts";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
deriveAuthClientMetadata,
signPayload,
timingSafeEqualBase64Url,
} from "./utils.ts";
/**
* The OAuth authorization server MCP clients (Claude Code, Codex, any agent
* T3 Code did not launch) use to sign in to this environment's `/mcp`.
*
* Every URL is derived from the request's own origin, so the same server
* answers correctly over loopback, Tailscale Serve and a T3 Connect tunnel.
* Client registration is stateless: a client id is its signed metadata, so
* an unauthenticated caller cannot grow server state. Only loopback redirect
* URIs are accepted; an https redirect would let anyone mail the owner an
* approval link that delivers the code to their own server.
*/
const SIGNING_SECRET_NAME = "mcp-oauth-signing-key";
const AUTHORIZATION_CODE_TTL_MS = 60_000;
const MAX_CLIENT_NAME_LENGTH = 100;
const MAX_REDIRECT_URIS = 5;
const MAX_REDIRECT_URI_LENGTH = 512;
const DEFAULT_CLIENT_NAME = "MCP client";
const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/;
const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/;
const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
export interface McpOAuthUrls {
readonly issuer: string;
readonly resource: string;
}
/**
* Issuer and MCP resource for the origin this request reached: its Host, and
* https when a proxy says so. A Host that is not a valid authority falls back
* to localhost, which no client will have asked for.
*/
export const requestUrls = (request: HttpServerRequest.HttpServerRequest): McpOAuthUrls => {
const origin = Option.match(HttpServerRequest.toURL(request), {
onNone: () => "http://localhost",
onSome: (url) => url.origin,
});
return { issuer: origin, resource: `${origin}/mcp` };
};
export const protectedResourceMetadata = (
urls: McpOAuthUrls,
): AuthMcpProtectedResourceMetadata => ({
resource: urls.resource,
authorization_servers: [urls.issuer],
scopes_supported: MCP_OAUTH_SCOPES,
bearer_methods_supported: ["header"],
resource_name: "T3 Code",
});
export const authorizationServerMetadata = (
urls: McpOAuthUrls,
): AuthMcpAuthorizationServerMetadata => ({
issuer: urls.issuer,
authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`,
token_endpoint: `${urls.issuer}/oauth/mcp/token`,
registration_endpoint: `${urls.issuer}/oauth/mcp/register`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code"],
code_challenge_methods_supported: ["S256"],
token_endpoint_auth_methods_supported: ["none"],
scopes_supported: MCP_OAUTH_SCOPES,
authorization_response_iss_parameter_supported: true,
});
const parseLoopbackRedirect = (value: string): URL | undefined => {
if (value.length > MAX_REDIRECT_URI_LENGTH) return undefined;
try {
const url = new URL(value);
return url.protocol === "http:" &&
LOOPBACK_HOSTNAMES.has(url.hostname) &&
url.username === "" &&
url.password === "" &&
url.hash === ""
? url
: undefined;
} catch {
return undefined;
}
};
/** RFC 8252 §7.3: loopback redirects match on everything but the port. */
export const loopbackRedirectMatches = (registered: string, presented: string): boolean => {
const left = parseLoopbackRedirect(registered);
const right = parseLoopbackRedirect(presented);
return (
left !== undefined &&
right !== undefined &&
left.hostname === right.hostname &&
left.pathname === right.pathname &&
left.search === right.search
);
};
const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => {
if (presented === undefined) return true;
try {
const url = new URL(presented);
return url.hash === "" && `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource;
} catch {
return false;
}
};
const ClientIdPayload = Schema.Struct({
v: Schema.Literal(1),
n: Schema.String,
r: Schema.Array(Schema.String),
});
const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload));
export interface McpOAuthClient {
readonly clientId: string;
readonly name: string;
readonly redirectUris: ReadonlyArray<string>;
}
/** Problems the authorize page shows the user without redirecting anywhere. */
export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()(
"McpOAuthPageError",
{ description: Schema.String },
) {
override get message(): string {
return this.description;
}
}
/** Problems reported back to the client through its (validated) redirect URI. */
export class McpOAuthRedirectError extends Schema.TaggedError<McpOAuthRedirectError>()(
"McpOAuthRedirectError",
{
error: Schema.Literals(["invalid_request", "unsupported_response_type", "invalid_target"]),
description: Schema.String,
redirectUri: Schema.String,
state: Schema.optional(Schema.String),
},
) {}
export interface AuthorizationRequest {
readonly client: McpOAuthClient;
readonly redirectUri: string;
readonly codeChallenge: string;
readonly state: string | undefined;
readonly resource: string;
readonly issuer: string;
}
interface PendingCode {
readonly clientId: string;
readonly clientName: string;
readonly redirectUri: string;
readonly codeChallenge: string;
readonly resource: string;
readonly access: AuthMcpClientAccess;
readonly expiresAtMs: number;
}
export type ApprovalDecision = Exclude<AuthMcpApprovalDecision, { readonly _tag: "deny" }>;
export class McpOAuth extends Context.Service<
McpOAuth,
{
readonly register: (
input: AuthMcpClientRegistration,
) => Effect.Effect<McpOAuthClient, AuthMcpRegistrationError>;
/** Validates an authorize request. Page errors must never redirect. */
readonly validateAuthorization: (input: {
readonly urls: McpOAuthUrls;
readonly request: AuthMcpAuthorizationRequest;
}) => Effect.Effect<AuthorizationRequest, McpOAuthPageError | McpOAuthRedirectError>;
/**
* The signed-in owner on this origin, when their browser session may
* approve at least read-only access. `approve` checks the chosen access
* against the session's scopes.
*/
readonly approvingBrowserSession: (
request: HttpServerRequest.HttpServerRequest,
authorization: AuthorizationRequest,
) => Effect.Effect<
| { readonly csrfToken: string; readonly scopes: ReadonlyArray<AuthEnvironmentScope> }
| undefined
>;
/** Approves and returns the URL to send the browser to. */
readonly approve: (input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly authorization: AuthorizationRequest;
readonly decision: ApprovalDecision;
}) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>;
readonly deny: (authorization: AuthorizationRequest) => string;
readonly exchangeCode: (input: {
readonly request: HttpServerRequest.HttpServerRequest;
readonly urls: McpOAuthUrls;
readonly token: AuthMcpTokenRequest;
}) => Effect.Effect<AuthMcpTokenResult, AuthMcpTokenError>;
}
>()("t3/auth/McpOAuth") {}
/** Appends OAuth response parameters, keeping any the client put in its redirect URI. */
const redirectWith = (redirectUri: string, params: Record<string, string | undefined>) => {
const url = new URL(redirectUri);
for (const [name, value] of Object.entries(params)) {
if (value !== undefined) url.searchParams.set(name, value);
}
return url.toString();
};
export const redirectForError = (error: McpOAuthRedirectError, issuer: string) =>
redirectWith(error.redirectUri, {
error: error.error,
error_description: error.description,
state: error.state,
iss: issuer,
});
const make = Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const secretStore = yield* ServerSecretStore.ServerSecretStore;
const crypto = yield* Crypto.Crypto;
const signingKey = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.orDie);
const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map());
const sign = (domain: string, payload: string) => signPayload(`${domain}.${payload}`, signingKey);
const signClientId = (name: string, redirectUris: ReadonlyArray<string>) => {
const body = base64UrlEncode(JSON.stringify({ v: 1, n: name, r: redirectUris }));
return `${body}.${sign("mcp-client-id", body)}`;
};
const parseClientId = (clientId: string): McpOAuthClient | undefined => {
const [body, signature, extra] = clientId.split(".");
if (!body || !signature || extra !== undefined) return undefined;
if (!timingSafeEqualBase64Url(signature, sign("mcp-client-id", body))) return undefined;
let json: string;
try {
json = base64UrlDecodeUtf8(body);
} catch {
return undefined;
}
return Option.getOrUndefined(
decodeClientIdPayload(json).pipe(
Option.map((payload) => ({ clientId, name: payload.n, redirectUris: payload.r })),
),
);
};
const pkceVerifies = (verifier: string, challenge: string) =>
CODE_VERIFIER_PATTERN.test(verifier)
? crypto.digest("SHA-256", new TextEncoder().encode(verifier)).pipe(
Effect.orDie,
Effect.map((digest) => timingSafeEqualBase64Url(base64UrlEncode(digest), challenge)),
)
: Effect.succeed(false);
const csrfToken = (sessionId: string, authorization: AuthorizationRequest) =>
sign(
"mcp-csrf",
JSON.stringify([
sessionId,
authorization.client.clientId,
authorization.redirectUri,
authorization.codeChallenge,
]),
);
const register: McpOAuth["Service"]["register"] = (metadata) =>
Effect.gen(function* () {
const rawName = metadata.client_name?.trim() ?? "";
const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice(
0,
MAX_CLIENT_NAME_LENGTH,
);
const redirectUris = metadata.redirect_uris ?? [];
if (redirectUris.length === 0 || redirectUris.length > MAX_REDIRECT_URIS) {
return yield* new AuthMcpRegistrationError({
error: "invalid_redirect_uri",
error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`,
});
}
if (!redirectUris.every((uri) => parseLoopbackRedirect(uri) !== undefined)) {
return yield* new AuthMcpRegistrationError({
error: "invalid_redirect_uri",
error_description:
"Only http://localhost, 127.0.0.1 or [::1] redirect URIs are accepted.",
});
}
if (
metadata.token_endpoint_auth_method !== undefined &&
metadata.token_endpoint_auth_method !== "none"
) {
return yield* new AuthMcpRegistrationError({
error: "invalid_client_metadata",
error_description: "Only public clients (token_endpoint_auth_method none) are supported.",
});
}
// Requested grant types and scopes are ignored rather than rejected: RFC 7591 lets
// the server answer with what it supports, and Claude Code asks for refresh_token.
return { clientId: signClientId(name, redirectUris), name, redirectUris };
});
const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = ({ urls, request }) =>
Effect.gen(function* () {
const client = parseClientId(request.client_id ?? "");
if (client === undefined) {
return yield* new McpOAuthPageError({
description: "This sign-in link names an unknown app. Start the sign-in again from it.",
});
}
const redirectUri = request.redirect_uri;
if (
redirectUri === undefined ||
parseLoopbackRedirect(redirectUri) === undefined ||
!client.redirectUris.some((registered) => loopbackRedirectMatches(registered, redirectUri))
) {
return yield* new McpOAuthPageError({
description: "This sign-in link sends you to an address the app did not register.",
});
}
const state = request.state;
const fail = (error: McpOAuthRedirectError["error"], description: string) =>
new McpOAuthRedirectError({
error,
description,
redirectUri,
...(state === undefined ? {} : { state }),
});
if (request.response_type !== "code") {
return yield* fail("unsupported_response_type", "Only response_type=code is supported.");
}
const codeChallenge = request.code_challenge;
if (
request.code_challenge_method !== "S256" ||
codeChallenge === undefined ||
!CODE_CHALLENGE_PATTERN.test(codeChallenge)
) {
return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required.");
}
if (!sameResource(urls, request.resource)) {
return yield* fail(
"invalid_target",
`This server only issues tokens for ${urls.resource}.`,
);
}
return {
client,
redirectUri,
codeChallenge,
state,
resource: urls.resource,
issuer: urls.issuer,
} satisfies AuthorizationRequest;
});
const approvingBrowserSession: McpOAuth["Service"]["approvingBrowserSession"] = (
request,
authorization,
) =>
environmentAuth.authenticateBrowserSession(request).pipe(
Effect.map((session) =>
// Approving manages access, and a session may only hand out scopes it holds.
session.scopes.includes(AuthAccessWriteScope) &&
session.scopes.includes(AuthOrchestrationReadScope)
? { csrfToken: csrfToken(session.sessionId, authorization), scopes: session.scopes }
: undefined,
),
Effect.orElseSucceed(() => undefined),
);
const mintCode = (authorization: AuthorizationRequest, access: AuthMcpClientAccess) =>
Effect.gen(function* () {
const now = yield* Clock.currentTimeMillis;
const code = Buffer.from(yield* crypto.randomBytes(32).pipe(Effect.orDie)).toString(
"base64url",
);
yield* Ref.update(codes, (current) => {
const next = new Map(
Array.from(current).filter(([, pending]) => pending.expiresAtMs > now),
);
next.set(code, {
clientId: authorization.client.clientId,
clientName: authorization.client.name,
redirectUri: authorization.redirectUri,
codeChallenge: authorization.codeChallenge,
resource: authorization.resource,
access,
expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS,
});
return next;
});
return code;
});
const approve: McpOAuth["Service"]["approve"] = (input) =>
Effect.gen(function* () {
const { decision } = input;
if (decision._tag === "pairing-code") {
yield* environmentAuth.consumeMcpApprovalCode(decision.code, decision.access).pipe(
Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) =>
Effect.logError("MCP approval code check failed.", { cause }).pipe(
Effect.andThen(
Effect.fail(
new McpOAuthPageError({
description: "The code could not be checked. Try again.",
}),
),
),
),
),
);
} else {
const session = yield* approvingBrowserSession(input.request, input.authorization);
if (
session === undefined ||
!timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) ||
!EnvironmentAuth.mcpClientScopes(decision.access).every((scope) =>
session.scopes.includes(scope),
)
) {
return yield* new McpOAuthPageError({
description: "Your session cannot approve this request. Enter a pairing code instead.",
});
}
}
const code = yield* mintCode(input.authorization, decision.access);
yield* Effect.logInfo("Approved an MCP client sign-in.", {
client: input.authorization.client.name,
access: decision.access,
method: decision._tag,
});
return redirectWith(input.authorization.redirectUri, {
code,
state: input.authorization.state,
iss: input.authorization.issuer,
});
});
const deny: McpOAuth["Service"]["deny"] = (authorization) =>
redirectWith(authorization.redirectUri, {
error: "access_denied",
state: authorization.state,
iss: authorization.issuer,
});
const exchangeCode: McpOAuth["Service"]["exchangeCode"] = ({ request, urls, token }) =>
Effect.gen(function* () {
const fail = (error: AuthMcpTokenError["error"], description: string) =>
new AuthMcpTokenError({ error, error_description: description });
if (token.grant_type !== "authorization_code") {
return yield* fail("unsupported_grant_type", "Only authorization_code is supported.");
}
const { code, redirect_uri: redirectUri, client_id: clientId } = token;
const verifier = token.code_verifier;
if (!code || !redirectUri || !clientId || !verifier) {
return yield* fail(
"invalid_request",
"code, redirect_uri, client_id and code_verifier are required.",
);
}
if (parseClientId(clientId) === undefined) {
return yield* fail("invalid_client", "The client is unknown.");
}
// A presented code is spent even when a later check fails (RFC 6749 §4.1.2).
const pending = yield* Ref.modify(codes, (current) => {
const found = current.get(code);
if (found === undefined) return [undefined, current] as const;
const next = new Map(current);
next.delete(code);
return [found, next] as const;
});
const now = yield* Clock.currentTimeMillis;
if (
pending === undefined ||
pending.expiresAtMs <= now ||
pending.clientId !== clientId ||
pending.redirectUri !== redirectUri ||
pending.resource !== urls.resource ||
!sameResource(urls, token.resource) ||
!(yield* pkceVerifies(verifier, pending.codeChallenge))
) {
return yield* fail("invalid_grant", "The authorization code is invalid or expired.");
}
const issued = yield* environmentAuth
.issueMcpClientSession({
label: pending.clientName,
access: pending.access,
client: deriveAuthClientMetadata({ request }),
})
.pipe(
Effect.catch((cause) =>
Effect.logError("Could not issue an MCP client session.", { cause }).pipe(
Effect.andThen(
Effect.fail(fail("invalid_grant", "The session could not be issued.")),
),
),
),
);
return {
access_token: issued.token,
token_type: "Bearer",
expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)),
scope: encodeOAuthScope(EnvironmentAuth.mcpClientScopes(pending.access)),
};
});
return McpOAuth.of({
register,
validateAuthorization,
approvingBrowserSession,
approve,
deny,
exchangeCode,
});
});
export const layer = Layer.effect(McpOAuth, make);
/**
* Lets `/mcp` admit OAuth clients. Their scope has no calling thread, and
* never carries preview or device access: those tools act on the caller's
* own thread.
*/
export const layerMcpClientAuthenticator = Layer.effect(
McpHttpServer.McpClientAuthenticator,
Effect.gen(function* () {
const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
const environment = yield* ServerEnvironment.ServerEnvironment;
const environmentId = yield* environment.getEnvironmentId;
return McpHttpServer.McpClientAuthenticator.of({
authenticate: (request) =>
environmentAuth.authenticateMcpClient(request).pipe(
Effect.flatMap((client) =>
Clock.currentTimeMillis.pipe(
Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({
environmentId,
requestNamespace: `client:${client.sessionId}`,
thread: undefined,
client: {
sessionId: client.sessionId,
label: client.label,
access: client.access,
},
capabilities: new Set<McpInvocationContext.McpCapability>([
"orchestration",
"worktree",
"pull-requests",
]),
issuedAt,
})),
),
),
Effect.catch((error) =>
(EnvironmentAuth.isServerAuthCredentialError(error)
? Effect.void
: Effect.logWarning("MCP client authentication failed.", { cause: error })
).pipe(Effect.as(undefined)),
),
),
});
}),
);
+14
View File
@@ -276,6 +276,20 @@ it.layer(NodeServices.layer)("SessionStore.layer", (it) => {
expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString());
}).pipe(Effect.provide(layerSessionStore())),
);
it.effect("carries a runtime-mode ceiling only on sessions issued with one", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
const capped = yield* sessions.issue({
subject: "mcp-client",
method: "bearer-access-token",
runtimeModeCeiling: "auto",
});
const uncapped = yield* sessions.issue({ method: "bearer-access-token" });
expect((yield* sessions.verify(capped.token)).runtimeModeCeiling).toBe("auto");
expect((yield* sessions.verify(uncapped.token)).runtimeModeCeiling).toBeUndefined();
}).pipe(Effect.provide(layerSessionStore())),
);
it.effect("rejects malformed session tokens", () =>
Effect.gen(function* () {
const sessions = yield* SessionStore.SessionStore;
+7
View File
@@ -7,6 +7,7 @@ import {
type AuthClientSession,
type AuthEnvironmentScope,
type ClientSurface,
RuntimeMode,
type ServerAuthSessionMethod,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
@@ -58,6 +59,8 @@ export interface VerifiedSession {
readonly subject: string;
readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
readonly proofKeyThumbprint?: string;
/** The most an MCP client approved through OAuth may hand to the threads it drives. */
readonly runtimeModeCeiling?: RuntimeMode;
}
export type SessionCredentialChange =
@@ -374,6 +377,7 @@ export class SessionStore extends Context.Service<
readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
readonly client?: AuthClientMetadata;
readonly proofKeyThumbprint?: string;
readonly runtimeModeCeiling?: RuntimeMode;
/**
* Atomically revoke active sessions with the same subject and method
* before storing this session.
@@ -430,6 +434,7 @@ const SessionClaims = Schema.Struct({
scopes: AuthEnvironmentScopes,
method: Schema.Literals(["browser-session-cookie", "bearer-access-token", "dpop-access-token"]),
jkt: Schema.optionalKey(Schema.String),
rtc: Schema.optionalKey(RuntimeMode),
iat: Schema.Number,
exp: Schema.Number,
});
@@ -665,6 +670,7 @@ export const make = Effect.gen(function* () {
scopes: input?.scopes ?? AuthStandardClientScopes,
method: input?.method ?? "browser-session-cookie",
...(input?.proofKeyThumbprint ? { jkt: input.proofKeyThumbprint } : {}),
...(input?.runtimeModeCeiling ? { rtc: input.runtimeModeCeiling } : {}),
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
@@ -839,6 +845,7 @@ export const make = Effect.gen(function* () {
subject: claims.sub,
scopes: claims.scopes,
...(claims.jkt ? { proofKeyThumbprint: claims.jkt } : {}),
...(claims.rtc ? { runtimeModeCeiling: claims.rtc } : {}),
} satisfies VerifiedSession;
},
);
+46
View File
@@ -0,0 +1,46 @@
/**
* The page for a sign-in link that cannot be trusted (unknown client or
* unregistered redirect). It is plain server HTML so it never depends on the
* web app, and it must not redirect anywhere.
*/
const escapeHtml = (value: string) =>
value.replace(
/[&<>"']/gu,
(character) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[character]!,
);
const STYLES = `
:root { color-scheme: light dark; font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 32px 16px; background: #f6f7f9; color: #17191f; }
main { width: min(100%, 440px); }
h1 { margin: 0 0 8px; font-size: 20px; }
p { margin: 0 0 12px; line-height: 1.5; color: #4b5060; }
@media (prefers-color-scheme: dark) {
body { background: #0f1115; color: #e6e8ee; }
p { color: #a0a6b4; }
}
`;
const shell = (title: string, body: string) => `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>${escapeHtml(title)}</title>
<style>${STYLES}</style>
</head>
<body>
<main>${body}</main>
</body>
</html>`;
export function renderErrorPage(description: string): string {
return shell(
"Sign-in failed",
`<h1>This sign-in cannot continue</h1>
<p>${escapeHtml(description)}</p>
<p>Close this page and start the sign-in again from your agent.</p>`,
);
}
+159
View File
@@ -0,0 +1,159 @@
import {
AuthMcpApprovalError,
type AuthMcpAuthorizationRequest,
AuthMcpClientAccess,
EnvironmentHttpApi,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Result from "effect/Result";
import { HttpServerRequest, HttpServerResponse } from "effect/http";
import * as HttpEffect from "effect/http/HttpEffect";
import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
import * as EnvironmentAuth from "./EnvironmentAuth.ts";
import * as McpOAuth from "./McpOAuth.ts";
import { renderErrorPage } from "./mcpOAuthHtml.ts";
/** Where the approval page lives in the web app. */
const APPROVAL_PAGE_PATH = "/connect-agent";
const PAGE_HEADERS = {
"content-security-policy":
"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
"x-frame-options": "DENY",
"cache-control": "no-store",
"referrer-policy": "no-referrer",
"x-content-type-options": "nosniff",
};
/** OAuth responses carry codes, tokens and client ids, none of which may be cached. */
const noStore = HttpEffect.appendPreResponseHandler((_request, response) =>
Effect.succeed(
HttpServerResponse.setHeaders(response, { "cache-control": "no-store", pragma: "no-cache" }),
),
);
/** Issuer and resource for the origin this request reached. */
const requestUrls = Effect.map(HttpServerRequest.HttpServerRequest, McpOAuth.requestUrls);
/**
* Validates the request the approval page forwards. An unverified client or
* redirect is reported, never redirected; any other problem goes back to the
* agent through its (verified) redirect URI.
*/
const forwardedAuthorization = (
oauth: McpOAuth.McpOAuth["Service"],
request: AuthMcpAuthorizationRequest,
) =>
Effect.gen(function* () {
const urls = yield* requestUrls;
return yield* oauth.validateAuthorization({ urls, request }).pipe(
Effect.catchTags({
McpOAuthPageError: (error) =>
Effect.fail(new AuthMcpApprovalError({ message: error.description })),
McpOAuthRedirectError: (error) =>
Effect.succeed({ redirectTo: McpOAuth.redirectForError(error, urls.issuer) }),
}),
);
});
export const layer = HttpApiBuilder.group(
EnvironmentHttpApi,
"mcpOAuth",
Effect.fnUntraced(function* (handlers) {
const oauth = yield* McpOAuth.McpOAuth;
const protectedResource = () =>
requestUrls.pipe(Effect.map(McpOAuth.protectedResourceMetadata));
return (
handlers
.handle("protectedResource", protectedResource)
.handle("mcpProtectedResource", protectedResource)
.handle("authorizationServer", () =>
requestUrls.pipe(Effect.map(McpOAuth.authorizationServerMetadata)),
)
.handle("register", ({ payload }) =>
oauth.register(payload).pipe(
Effect.map((client) => ({
client_id: client.clientId,
client_name: client.name,
redirect_uris: client.redirectUris,
grant_types: ["authorization_code" as const],
response_types: ["code" as const],
token_endpoint_auth_method: "none" as const,
})),
Effect.tap(() => noStore),
),
)
// The browser lands here from the agent. A valid request is handed to the
// web app's approval page with its query intact.
.handleRaw("authorize", ({ request }) =>
Effect.gen(function* () {
const urls = yield* requestUrls;
const url = new URL(request.url, urls.issuer);
const authorization = yield* oauth
.validateAuthorization({ urls, request: Object.fromEntries(url.searchParams) })
.pipe(Effect.result);
const headers = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
if (Result.isSuccess(authorization)) {
return HttpServerResponse.redirect(`${APPROVAL_PAGE_PATH}${url.search}`, { headers });
}
const error = authorization.failure;
return error._tag === "McpOAuthPageError"
? HttpServerResponse.text(renderErrorPage(error.description), {
status: 400,
contentType: "text/html; charset=utf-8",
headers: PAGE_HEADERS,
})
: HttpServerResponse.redirect(McpOAuth.redirectForError(error, urls.issuer), {
headers,
});
}),
)
// What the approval page shows, and whether one click may approve.
.handle("approval", ({ payload, request }) =>
Effect.gen(function* () {
const resolved = yield* forwardedAuthorization(oauth, payload);
if ("redirectTo" in resolved) return resolved;
const urls = yield* requestUrls;
const session = yield* oauth.approvingBrowserSession(request, resolved);
yield* noStore;
return {
clientName: resolved.client.name,
redirectHost: new URL(resolved.redirectUri).host,
environmentHost: new URL(urls.issuer).host,
...(session === undefined
? {}
: {
csrfToken: session.csrfToken,
oneClickAccess: AuthMcpClientAccess.literals.filter((access) =>
EnvironmentAuth.mcpClientScopes(access).every((scope) =>
session.scopes.includes(scope),
),
),
}),
};
}),
)
.handle("decision", ({ payload, request }) =>
Effect.gen(function* () {
const resolved = yield* forwardedAuthorization(oauth, payload.authorization);
if ("redirectTo" in resolved) return resolved;
yield* noStore;
const { decision } = payload;
if (decision._tag === "deny") return { redirectTo: oauth.deny(resolved) };
return yield* oauth.approve({ request, authorization: resolved, decision }).pipe(
Effect.map((redirectTo) => ({ redirectTo })),
Effect.mapError((error) => new AuthMcpApprovalError({ message: error.message })),
);
}),
)
.handle("token", ({ payload, request }) =>
Effect.gen(function* () {
yield* noStore;
return yield* oauth.exchangeCode({ request, urls: yield* requestUrls, token: payload });
}),
)
);
}),
);