The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | AuthAccessWriteScope, |
| 3 | type AuthMcpApprovalDecision, |
| 4 | type AuthMcpAuthorizationRequest, |
| 5 | type AuthMcpAuthorizationServerMetadata, |
| 6 | type AuthMcpClientRegistration, |
| 7 | type AuthMcpProtectedResourceMetadata, |
| 8 | AuthMcpRegistrationError, |
| 9 | AuthMcpTokenError, |
| 10 | type AuthMcpTokenRequest, |
| 11 | type AuthMcpTokenResult, |
| 12 | type AuthMcpClientAccess, |
| 13 | type AuthEnvironmentScope, |
| 14 | AuthOrchestrationOperateScope, |
| 15 | AuthOrchestrationReadScope, |
| 16 | MCP_PEER_LINK_SOFTWARE_ID, |
| 17 | mcpClientScopes, |
| 18 | parseMcpApprovalCode, |
| 19 | type RuntimeMode, |
| 20 | } from "@t3tools/contracts"; |
| 21 | import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth"; |
| 22 | import { encodeOAuthScope } from "@t3tools/shared/oauthScope"; |
| 23 | import * as Clock from "effect/Clock"; |
| 24 | import * as Context from "effect/Context"; |
| 25 | import * as Digest from "effect/crypto/Digest"; |
| 26 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 27 | import * as Effect from "effect/Effect"; |
| 28 | import * as Layer from "effect/Layer"; |
| 29 | import * as Option from "effect/Option"; |
| 30 | import * as Redacted from "effect/Redacted"; |
| 31 | import * as Ref from "effect/Ref"; |
| 32 | import * as Schema from "effect/Schema"; |
| 33 | import { HttpServerRequest } from "effect/http"; |
| 34 | |
| 35 | import { hostedAppUrlConfig } from "../cloud/publicConfig.ts"; |
| 36 | import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; |
| 37 | import * as ServerSettings from "../serverSettings.ts"; |
| 38 | import * as McpHttpServer from "../mcp/McpHttpServer.ts"; |
| 39 | import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; |
| 40 | import * as PayloadSigner from "./PayloadSigner.ts"; |
| 41 | import * as EnvironmentAuth from "./EnvironmentAuth.ts"; |
| 42 | import * as ServerSecretStore from "./ServerSecretStore.ts"; |
| 43 | import { |
| 44 | base64UrlDecodeUtf8, |
| 45 | base64UrlEncode, |
| 46 | deriveAuthClientMetadata, |
| 47 | timingSafeEqualBase64Url, |
| 48 | } from "./utils.ts"; |
| 49 | import { requestUrl } from "../requestUrl.ts"; |
| 50 | |
| 51 | // Request-derived origins support loopback, Tailscale and tunnels. |
| 52 | // Signed client metadata keeps unauthenticated registration stateless. |
| 53 | |
| 54 | const SIGNING_SECRET_NAME = "mcp-oauth-signing-key"; |
| 55 | const AUTHORIZATION_CODE_TTL_MS = 60_000; |
| 56 | const MAX_CLIENT_NAME_LENGTH = 100; |
| 57 | const MAX_REDIRECT_URIS = 10; |
| 58 | const MAX_REDIRECT_URI_LENGTH = 512; |
| 59 | // The client_id rides in the authorize URL. Past the original five-URI limit, cap it to leave room |
| 60 | // under Node's 16 KB header cap for an encoded redirect_uri and state. |
| 61 | const MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS = 5; |
| 62 | const MAX_CLIENT_ID_LENGTH = 10_240; |
| 63 | const DEFAULT_CLIENT_NAME = "MCP client"; |
| 64 | const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]); |
| 65 | const CODE_CHALLENGE_PATTERN = /^[A-Za-z0-9_-]{43}$/; |
| 66 | const CODE_VERIFIER_PATTERN = /^[A-Za-z0-9\-._~]{43,128}$/; |
| 67 | |
| 68 | const MCP_OAUTH_SCOPES = [AuthOrchestrationReadScope, AuthOrchestrationOperateScope]; |
| 69 | |
| 70 | export interface McpOAuthUrls { |
| 71 | readonly issuer: string; |
| 72 | readonly resource: string; |
| 73 | } |
| 74 | |
| 75 | export const requestUrls = (request: HttpServerRequest.HttpServerRequest): McpOAuthUrls => { |
| 76 | const origin = Option.match(requestUrl(request), { |
| 77 | onNone: () => "http://localhost", |
| 78 | onSome: (url) => url.origin, |
| 79 | }); |
| 80 | return { issuer: origin, resource: `${origin}/mcp` }; |
| 81 | }; |
| 82 | |
| 83 | export const protectedResourceMetadata = ( |
| 84 | urls: McpOAuthUrls, |
| 85 | ): AuthMcpProtectedResourceMetadata => ({ |
| 86 | resource: urls.resource, |
| 87 | authorization_servers: [urls.issuer], |
| 88 | scopes_supported: MCP_OAUTH_SCOPES, |
| 89 | bearer_methods_supported: ["header"], |
| 90 | resource_name: "T3 Code", |
| 91 | }); |
| 92 | |
| 93 | export const authorizationServerMetadata = ( |
| 94 | urls: McpOAuthUrls, |
| 95 | ): AuthMcpAuthorizationServerMetadata => ({ |
| 96 | issuer: urls.issuer, |
| 97 | authorization_endpoint: `${urls.issuer}/oauth/mcp/authorize`, |
| 98 | token_endpoint: `${urls.issuer}/oauth/mcp/token`, |
| 99 | registration_endpoint: `${urls.issuer}/oauth/mcp/register`, |
| 100 | response_types_supported: ["code"], |
| 101 | grant_types_supported: ["authorization_code"], |
| 102 | code_challenge_methods_supported: ["S256"], |
| 103 | token_endpoint_auth_methods_supported: ["none"], |
| 104 | scopes_supported: MCP_OAUTH_SCOPES, |
| 105 | authorization_response_iss_parameter_supported: true, |
| 106 | }); |
| 107 | |
| 108 | const parseRedirect = (value: string): URL | undefined => { |
| 109 | // URL.hash misses empty fragments, which RFC 6749 §3.1.2 also forbids. |
| 110 | if (value.length > MAX_REDIRECT_URI_LENGTH || value.includes("#")) return undefined; |
| 111 | try { |
| 112 | const url = new URL(value); |
| 113 | const allowed = |
| 114 | url.protocol === "https:" || |
| 115 | (url.protocol === "http:" && LOOPBACK_HOSTNAMES.has(url.hostname)); |
| 116 | return allowed && url.username === "" && url.password === "" ? url : undefined; |
| 117 | } catch { |
| 118 | return undefined; |
| 119 | } |
| 120 | }; |
| 121 | |
| 122 | /** Loopback redirects ignore port (RFC 8252 §7.3); HTTPS redirects match exactly. */ |
| 123 | export const redirectMatches = (registered: string, presented: string): boolean => { |
| 124 | const left = parseRedirect(registered); |
| 125 | const right = parseRedirect(presented); |
| 126 | if (left === undefined || right === undefined) return false; |
| 127 | if (left.protocol === "https:" || right.protocol === "https:") return left.href === right.href; |
| 128 | return ( |
| 129 | left.hostname === right.hostname && |
| 130 | left.pathname === right.pathname && |
| 131 | left.search === right.search |
| 132 | ); |
| 133 | }; |
| 134 | |
| 135 | const sameResource = (urls: McpOAuthUrls, presented: string | undefined): boolean => { |
| 136 | if (presented === undefined) return true; |
| 137 | // URL.hash misses empty fragments, which RFC 8707 §2 also forbids. |
| 138 | if (presented.includes("#")) return false; |
| 139 | try { |
| 140 | const url = new URL(presented); |
| 141 | return `${url.origin}${url.pathname.replace(/\/+$/u, "")}` === urls.resource; |
| 142 | } catch { |
| 143 | return false; |
| 144 | } |
| 145 | }; |
| 146 | |
| 147 | const ClientIdPayload = Schema.Struct({ |
| 148 | v: Schema.Literal(1), |
| 149 | n: Schema.String, |
| 150 | r: Schema.Array(Schema.String), |
| 151 | /** Registered as another T3 Code environment's peer link. */ |
| 152 | p: Schema.optionalKey(Schema.Literal(1)), |
| 153 | }); |
| 154 | const decodeClientIdPayload = Schema.decodeUnknownOption(Schema.fromJsonString(ClientIdPayload)); |
| 155 | |
| 156 | export interface McpOAuthClient { |
| 157 | readonly clientId: string; |
| 158 | readonly name: string; |
| 159 | readonly redirectUris: ReadonlyArray<string>; |
| 160 | readonly peerLink: boolean; |
| 161 | } |
| 162 | |
| 163 | export class McpOAuthPageError extends Schema.TaggedError<McpOAuthPageError>()( |
| 164 | "McpOAuthPageError", |
| 165 | { description: Schema.String }, |
| 166 | ) { |
| 167 | override get message(): string { |
| 168 | return this.description; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | export class McpOAuthRedirectError extends Schema.TaggedError<McpOAuthRedirectError>()( |
| 173 | "McpOAuthRedirectError", |
| 174 | { |
| 175 | error: Schema.Literals(["invalid_request", "unsupported_response_type", "invalid_target"]), |
| 176 | description: Schema.String, |
| 177 | redirectUri: Schema.String, |
| 178 | state: Schema.optional(Schema.RedactedFromValue(Schema.String)), |
| 179 | }, |
| 180 | ) {} |
| 181 | |
| 182 | export interface AuthorizationRequest { |
| 183 | readonly client: McpOAuthClient; |
| 184 | readonly redirectUri: string; |
| 185 | readonly codeChallenge: string; |
| 186 | readonly state: Redacted.Redacted<string> | undefined; |
| 187 | readonly resource: string; |
| 188 | readonly issuer: string; |
| 189 | } |
| 190 | |
| 191 | interface PendingCode { |
| 192 | readonly clientId: string; |
| 193 | readonly clientName: string; |
| 194 | readonly peerLink: boolean; |
| 195 | readonly redirectUri: string; |
| 196 | readonly codeChallenge: string; |
| 197 | readonly resource: string; |
| 198 | readonly access: AuthMcpClientAccess; |
| 199 | readonly expiresAtMs: number; |
| 200 | } |
| 201 | |
| 202 | export type ApprovalDecision = Exclude<AuthMcpApprovalDecision, { readonly _tag: "deny" }>; |
| 203 | |
| 204 | export class McpOAuth extends Context.Service< |
| 205 | McpOAuth, |
| 206 | { |
| 207 | readonly register: ( |
| 208 | input: AuthMcpClientRegistration, |
| 209 | ) => Effect.Effect<McpOAuthClient, AuthMcpRegistrationError>; |
| 210 | /** Page errors must never redirect. */ |
| 211 | readonly validateAuthorization: (input: { |
| 212 | readonly urls: McpOAuthUrls; |
| 213 | readonly request: AuthMcpAuthorizationRequest; |
| 214 | }) => Effect.Effect<AuthorizationRequest, McpOAuthPageError | McpOAuthRedirectError>; |
| 215 | /** A browser cookie session, or a T3 Connect session from the hosted app, that may approve. */ |
| 216 | readonly approvingSession: ( |
| 217 | request: HttpServerRequest.HttpServerRequest, |
| 218 | authorization: AuthorizationRequest, |
| 219 | ) => Effect.Effect< |
| 220 | | { readonly csrfToken: string; readonly scopes: ReadonlyArray<AuthEnvironmentScope> } |
| 221 | | undefined |
| 222 | >; |
| 223 | readonly approve: (input: { |
| 224 | readonly request: HttpServerRequest.HttpServerRequest; |
| 225 | readonly authorization: AuthorizationRequest; |
| 226 | readonly decision: ApprovalDecision; |
| 227 | }) => Effect.Effect<string, EnvironmentAuth.ServerAuthMcpApprovalCodeError | McpOAuthPageError>; |
| 228 | readonly deny: (authorization: AuthorizationRequest) => string; |
| 229 | /** A managed policy's runtime-mode ceiling, shown on the approval page. */ |
| 230 | readonly runtimeModeCeiling: |
| 231 | | { readonly organization: string; readonly maxRuntimeMode: RuntimeMode } |
| 232 | | undefined; |
| 233 | readonly exchangeCode: (input: { |
| 234 | readonly request: HttpServerRequest.HttpServerRequest; |
| 235 | readonly urls: McpOAuthUrls; |
| 236 | readonly token: AuthMcpTokenRequest; |
| 237 | }) => Effect.Effect<AuthMcpTokenResult, AuthMcpTokenError>; |
| 238 | } |
| 239 | >()("t3/auth/McpOAuth") {} |
| 240 | |
| 241 | const redirectWith = ( |
| 242 | redirectUri: string, |
| 243 | params: Record<string, string | Redacted.Redacted<string> | undefined>, |
| 244 | ) => { |
| 245 | const url = new URL(redirectUri); |
| 246 | for (const [name, value] of Object.entries(params)) { |
| 247 | if (value !== undefined) { |
| 248 | url.searchParams.set(name, Redacted.isRedacted(value) ? Redacted.value(value) : value); |
| 249 | } |
| 250 | } |
| 251 | return url.toString(); |
| 252 | }; |
| 253 | |
| 254 | export const redirectForError = (error: McpOAuthRedirectError, issuer: string) => |
| 255 | redirectWith(error.redirectUri, { |
| 256 | error: error.error, |
| 257 | error_description: error.description, |
| 258 | state: error.state, |
| 259 | iss: issuer, |
| 260 | }); |
| 261 | |
| 262 | const make = Effect.gen(function* () { |
| 263 | const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 264 | const secretStore = yield* ServerSecretStore.ServerSecretStore; |
| 265 | const random = yield* SecureRandom.SecureRandom; |
| 266 | const digester = yield* Digest.Digest; |
| 267 | const serverSettings = yield* ServerSettings.ServerSettingsService; |
| 268 | const linksEnabled = serverSettings.getSettings.pipe( |
| 269 | Effect.map((settings) => settings.linkedEnvironmentsEnabled), |
| 270 | Effect.orElseSucceed(() => false), |
| 271 | ); |
| 272 | const signer = yield* PayloadSigner.fromSecret( |
| 273 | yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32).pipe(Effect.orDie), |
| 274 | ); |
| 275 | const codes = yield* Ref.make<ReadonlyMap<string, PendingCode>>(new Map()); |
| 276 | |
| 277 | const sign = (domain: string, payload: string) => signer.sign(`${domain}.${payload}`); |
| 278 | |
| 279 | const signClientId = (name: string, redirectUris: ReadonlyArray<string>, peerLink: boolean) => { |
| 280 | const body = base64UrlEncode( |
| 281 | JSON.stringify({ v: 1, n: name, r: redirectUris, ...(peerLink ? { p: 1 } : {}) }), |
| 282 | ); |
| 283 | return sign("mcp-client-id", body).pipe(Effect.map((signature) => `${body}.${signature}`)); |
| 284 | }; |
| 285 | |
| 286 | // Untraced: only called inside the traced McpOAuth methods below. |
| 287 | const parseClientId = Effect.fnUntraced(function* ( |
| 288 | clientId: string, |
| 289 | ): Effect.fn.Return<McpOAuthClient | undefined> { |
| 290 | const [body, signature, extra] = clientId.split("."); |
| 291 | if (!body || !signature || extra !== undefined) return undefined; |
| 292 | const verified = yield* signer.verify(`mcp-client-id.${body}`, signature); |
| 293 | if (!verified) return undefined; |
| 294 | const json = Option.liftThrowable(base64UrlDecodeUtf8)(body); |
| 295 | if (Option.isNone(json)) return undefined; |
| 296 | return Option.getOrUndefined( |
| 297 | decodeClientIdPayload(json.value).pipe( |
| 298 | Option.map((payload) => ({ |
| 299 | clientId, |
| 300 | name: payload.n, |
| 301 | redirectUris: payload.r, |
| 302 | peerLink: payload.p === 1, |
| 303 | })), |
| 304 | ), |
| 305 | ); |
| 306 | }); |
| 307 | |
| 308 | const pkceVerifies = (verifier: string, challenge: string) => |
| 309 | CODE_VERIFIER_PATTERN.test(verifier) |
| 310 | ? digester.digest(Digest.sha256, new TextEncoder().encode(verifier)).pipe( |
| 311 | Effect.orDie, |
| 312 | Effect.map((digest) => timingSafeEqualBase64Url(base64UrlEncode(digest), challenge)), |
| 313 | ) |
| 314 | : Effect.succeed(false); |
| 315 | |
| 316 | const csrfToken = (holder: string, authorization: AuthorizationRequest) => |
| 317 | sign( |
| 318 | "mcp-csrf", |
| 319 | JSON.stringify([ |
| 320 | holder, |
| 321 | authorization.client.clientId, |
| 322 | authorization.redirectUri, |
| 323 | authorization.codeChallenge, |
| 324 | ]), |
| 325 | ); |
| 326 | |
| 327 | const register: McpOAuth["Service"]["register"] = Effect.fn("McpOAuth.register")( |
| 328 | function* (metadata) { |
| 329 | const rawName = metadata.client_name?.trim() ?? ""; |
| 330 | const name = (rawName.length > 0 ? rawName : DEFAULT_CLIENT_NAME).slice( |
| 331 | 0, |
| 332 | MAX_CLIENT_NAME_LENGTH, |
| 333 | ); |
| 334 | const redirectUris = metadata.redirect_uris ?? []; |
| 335 | if (redirectUris.length === 0 || redirectUris.length > MAX_REDIRECT_URIS) { |
| 336 | return yield* new AuthMcpRegistrationError({ |
| 337 | error: "invalid_redirect_uri", |
| 338 | error_description: `Register between 1 and ${MAX_REDIRECT_URIS} redirect URIs.`, |
| 339 | }); |
| 340 | } |
| 341 | if (!redirectUris.every((uri) => parseRedirect(uri) !== undefined)) { |
| 342 | return yield* new AuthMcpRegistrationError({ |
| 343 | error: "invalid_redirect_uri", |
| 344 | error_description: |
| 345 | "Redirect URIs must be https, or http on localhost, 127.0.0.1 or [::1].", |
| 346 | }); |
| 347 | } |
| 348 | // RFC 7591 allows ignoring unsupported registration options; all clients use public PKCE. |
| 349 | const peerLink = metadata.software_id === MCP_PEER_LINK_SOFTWARE_ID; |
| 350 | if (peerLink && !(yield* linksEnabled)) { |
| 351 | return yield* new AuthMcpRegistrationError({ |
| 352 | error: "invalid_client_metadata", |
| 353 | error_description: |
| 354 | "Linked environments is off on that machine. Turn it on in its Settings → Labs.", |
| 355 | }); |
| 356 | } |
| 357 | const clientId = yield* signClientId(name, redirectUris, peerLink); |
| 358 | if ( |
| 359 | redirectUris.length > MAX_UNBOUNDED_CLIENT_ID_REDIRECT_URIS && |
| 360 | clientId.length > MAX_CLIENT_ID_LENGTH |
| 361 | ) { |
| 362 | return yield* new AuthMcpRegistrationError({ |
| 363 | error: "invalid_redirect_uri", |
| 364 | error_description: "Redirect URIs are too long to fit in an authorization request.", |
| 365 | }); |
| 366 | } |
| 367 | return { |
| 368 | clientId, |
| 369 | name, |
| 370 | redirectUris, |
| 371 | peerLink, |
| 372 | }; |
| 373 | }, |
| 374 | ); |
| 375 | |
| 376 | const validateAuthorization: McpOAuth["Service"]["validateAuthorization"] = Effect.fn( |
| 377 | "McpOAuth.validateAuthorization", |
| 378 | )(function* ({ urls, request }) { |
| 379 | const client = yield* parseClientId(request.client_id ?? ""); |
| 380 | if (client === undefined) { |
| 381 | return yield* new McpOAuthPageError({ |
| 382 | description: "This sign-in link names an unknown app. Start the sign-in again from it.", |
| 383 | }); |
| 384 | } |
| 385 | const redirectUri = request.redirect_uri; |
| 386 | if ( |
| 387 | redirectUri === undefined || |
| 388 | !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri)) |
| 389 | ) { |
| 390 | return yield* new McpOAuthPageError({ |
| 391 | description: "This sign-in link sends you to an address the app did not register.", |
| 392 | }); |
| 393 | } |
| 394 | const state = request.state; |
| 395 | const fail = (error: McpOAuthRedirectError["error"], description: string) => |
| 396 | new McpOAuthRedirectError({ |
| 397 | error, |
| 398 | description, |
| 399 | redirectUri, |
| 400 | ...(state === undefined ? {} : { state }), |
| 401 | }); |
| 402 | if (request.response_type !== "code") { |
| 403 | return yield* fail("unsupported_response_type", "Only response_type=code is supported."); |
| 404 | } |
| 405 | const codeChallenge = request.code_challenge; |
| 406 | if ( |
| 407 | request.code_challenge_method !== "S256" || |
| 408 | codeChallenge === undefined || |
| 409 | !CODE_CHALLENGE_PATTERN.test(codeChallenge) |
| 410 | ) { |
| 411 | return yield* fail("invalid_request", "PKCE with code_challenge_method=S256 is required."); |
| 412 | } |
| 413 | if (!sameResource(urls, request.resource)) { |
| 414 | return yield* fail("invalid_target", `This server only issues tokens for ${urls.resource}.`); |
| 415 | } |
| 416 | return { |
| 417 | client, |
| 418 | redirectUri, |
| 419 | codeChallenge, |
| 420 | state, |
| 421 | resource: urls.resource, |
| 422 | issuer: urls.issuer, |
| 423 | } satisfies AuthorizationRequest; |
| 424 | }); |
| 425 | |
| 426 | const approvingSession: McpOAuth["Service"]["approvingSession"] = (request, authorization) => |
| 427 | environmentAuth.authenticateHttpRequest(request).pipe( |
| 428 | Effect.flatMap((session) => |
| 429 | // Approving manages access, and a session may only hand out scopes it holds. |
| 430 | session.scopes.includes(AuthAccessWriteScope) && |
| 431 | session.scopes.includes(AuthOrchestrationReadScope) |
| 432 | ? // The hosted app may get a fresh credential per call, all bound to one browser key. |
| 433 | csrfToken( |
| 434 | session.proofKeyThumbprint === undefined |
| 435 | ? session.sessionId |
| 436 | : `dpop:${session.proofKeyThumbprint}`, |
| 437 | authorization, |
| 438 | ).pipe(Effect.map((token) => ({ csrfToken: token, scopes: session.scopes }))) |
| 439 | : Effect.undefined, |
| 440 | ), |
| 441 | Effect.orElseSucceed(() => undefined), |
| 442 | ); |
| 443 | |
| 444 | const mintCode = Effect.fn("McpOAuth.mintCode")(function* ( |
| 445 | authorization: AuthorizationRequest, |
| 446 | access: AuthMcpClientAccess, |
| 447 | ) { |
| 448 | const now = yield* Clock.currentTimeMillis; |
| 449 | const code = Buffer.from(yield* random.randomBytes(32)).toString("base64url"); |
| 450 | yield* Ref.update(codes, (current) => { |
| 451 | const next = new Map(Array.from(current).filter(([, pending]) => pending.expiresAtMs > now)); |
| 452 | next.set(code, { |
| 453 | clientId: authorization.client.clientId, |
| 454 | clientName: authorization.client.name, |
| 455 | peerLink: authorization.client.peerLink, |
| 456 | redirectUri: authorization.redirectUri, |
| 457 | codeChallenge: authorization.codeChallenge, |
| 458 | resource: authorization.resource, |
| 459 | access, |
| 460 | expiresAtMs: now + AUTHORIZATION_CODE_TTL_MS, |
| 461 | }); |
| 462 | return next; |
| 463 | }); |
| 464 | return code; |
| 465 | }); |
| 466 | |
| 467 | const approve: McpOAuth["Service"]["approve"] = Effect.fn("McpOAuth.approve")(function* (input) { |
| 468 | const { decision } = input; |
| 469 | let access = decision.access; |
| 470 | if (decision._tag === "pairing-code") { |
| 471 | // An approval code is for one app's sign-in, never for linking another environment. |
| 472 | if (input.authorization.client.peerLink && parseMcpApprovalCode(decision.code)) { |
| 473 | return yield* new McpOAuthPageError({ |
| 474 | description: "Linking needs a plain pairing code, not an app approval code.", |
| 475 | }); |
| 476 | } |
| 477 | access = yield* environmentAuth |
| 478 | .consumeMcpApprovalCode(decision.code, decision.access, input.authorization.client.peerLink) |
| 479 | .pipe( |
| 480 | Effect.catchIf(EnvironmentAuth.isServerAuthInternalError, (cause) => |
| 481 | Effect.logError("MCP approval code check failed.", { cause }).pipe( |
| 482 | Effect.andThen( |
| 483 | Effect.fail( |
| 484 | new McpOAuthPageError({ |
| 485 | description: "The code could not be checked. Try again.", |
| 486 | }), |
| 487 | ), |
| 488 | ), |
| 489 | ), |
| 490 | ), |
| 491 | ); |
| 492 | } else { |
| 493 | const session = yield* approvingSession(input.request, input.authorization); |
| 494 | if ( |
| 495 | session === undefined || |
| 496 | !timingSafeEqualBase64Url(decision.csrfToken, session.csrfToken) || |
| 497 | !mcpClientScopes(decision.access).every((scope) => session.scopes.includes(scope)) |
| 498 | ) { |
| 499 | return yield* new McpOAuthPageError({ |
| 500 | description: "Your session cannot approve this request. Enter a pairing code instead.", |
| 501 | }); |
| 502 | } |
| 503 | } |
| 504 | const code = yield* mintCode(input.authorization, access); |
| 505 | yield* Effect.logInfo("Approved an MCP client sign-in.", { |
| 506 | client: input.authorization.client.name, |
| 507 | access, |
| 508 | method: decision._tag, |
| 509 | }); |
| 510 | return redirectWith(input.authorization.redirectUri, { |
| 511 | code, |
| 512 | state: input.authorization.state, |
| 513 | iss: input.authorization.issuer, |
| 514 | }); |
| 515 | }); |
| 516 | |
| 517 | const deny: McpOAuth["Service"]["deny"] = (authorization) => |
| 518 | redirectWith(authorization.redirectUri, { |
| 519 | error: "access_denied", |
| 520 | state: authorization.state, |
| 521 | iss: authorization.issuer, |
| 522 | }); |
| 523 | |
| 524 | const exchangeCode: McpOAuth["Service"]["exchangeCode"] = Effect.fn("McpOAuth.exchangeCode")( |
| 525 | function* ({ request, urls, token }) { |
| 526 | const fail = (error: AuthMcpTokenError["error"], description: string) => |
| 527 | new AuthMcpTokenError({ error, error_description: description }); |
| 528 | if (token.grant_type !== "authorization_code") { |
| 529 | return yield* fail("unsupported_grant_type", "Only authorization_code is supported."); |
| 530 | } |
| 531 | const { redirect_uri: redirectUri, client_id: clientId } = token; |
| 532 | const code = token.code && Redacted.value(token.code); |
| 533 | const verifier = token.code_verifier && Redacted.value(token.code_verifier); |
| 534 | if (!code || !redirectUri || !clientId || !verifier) { |
| 535 | return yield* fail( |
| 536 | "invalid_request", |
| 537 | "code, redirect_uri, client_id and code_verifier are required.", |
| 538 | ); |
| 539 | } |
| 540 | if ((yield* parseClientId(clientId)) === undefined) { |
| 541 | return yield* fail("invalid_client", "The client is unknown."); |
| 542 | } |
| 543 | // A presented code is spent even when a later check fails (RFC 6749 §4.1.2). |
| 544 | const pending = yield* Ref.modify(codes, (current) => { |
| 545 | const found = current.get(code); |
| 546 | if (found === undefined) return [undefined, current] as const; |
| 547 | const next = new Map(current); |
| 548 | next.delete(code); |
| 549 | return [found, next] as const; |
| 550 | }); |
| 551 | const now = yield* Clock.currentTimeMillis; |
| 552 | if ( |
| 553 | pending === undefined || |
| 554 | pending.expiresAtMs <= now || |
| 555 | pending.clientId !== clientId || |
| 556 | pending.redirectUri !== redirectUri || |
| 557 | pending.resource !== urls.resource || |
| 558 | !sameResource(urls, token.resource) || |
| 559 | !(yield* pkceVerifies(verifier, pending.codeChallenge)) |
| 560 | ) { |
| 561 | return yield* fail("invalid_grant", "The authorization code is invalid or expired."); |
| 562 | } |
| 563 | const issued = yield* environmentAuth |
| 564 | .issueMcpClientSession({ |
| 565 | label: pending.clientName, |
| 566 | access: pending.access, |
| 567 | peerLink: pending.peerLink, |
| 568 | client: deriveAuthClientMetadata({ request }), |
| 569 | }) |
| 570 | .pipe( |
| 571 | Effect.catch((cause) => |
| 572 | Effect.logError("Could not issue an MCP client session.", { cause }).pipe( |
| 573 | Effect.andThen( |
| 574 | Effect.fail(fail("invalid_grant", "The session could not be issued.")), |
| 575 | ), |
| 576 | ), |
| 577 | ), |
| 578 | ); |
| 579 | return { |
| 580 | access_token: issued.token, |
| 581 | token_type: "Bearer", |
| 582 | expires_in: Math.max(0, Math.floor((issued.expiresAt.epochMilliseconds - now) / 1000)), |
| 583 | scope: encodeOAuthScope(mcpClientScopes(pending.access)), |
| 584 | }; |
| 585 | }, |
| 586 | ); |
| 587 | |
| 588 | const managedPolicy = serverSettings.managedPolicy; |
| 589 | const maxRuntimeMode = managedPolicy?.limits?.maxRuntimeMode; |
| 590 | return McpOAuth.of({ |
| 591 | runtimeModeCeiling: |
| 592 | managedPolicy === undefined || maxRuntimeMode === undefined |
| 593 | ? undefined |
| 594 | : { organization: managedPolicy.organization, maxRuntimeMode }, |
| 595 | register, |
| 596 | validateAuthorization, |
| 597 | approvingSession, |
| 598 | approve, |
| 599 | deny, |
| 600 | exchangeCode, |
| 601 | }); |
| 602 | }); |
| 603 | |
| 604 | export const layer = Layer.effect(McpOAuth, make); |
| 605 | |
| 606 | export const layerMcpClientAuthenticator = Layer.effect( |
| 607 | McpHttpServer.McpClientAuthenticator, |
| 608 | Effect.gen(function* () { |
| 609 | const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; |
| 610 | const environment = yield* ServerEnvironment.ServerEnvironment; |
| 611 | const environmentId = yield* environment.getEnvironmentId; |
| 612 | const hostedAppUrl = yield* hostedAppUrlConfig.pipe( |
| 613 | Effect.catch((cause) => |
| 614 | Effect.logWarning("Outside MCP clients get app.t3.codes thread links", { cause }).pipe( |
| 615 | Effect.as(DEFAULT_HOSTED_APP_URL), |
| 616 | ), |
| 617 | ), |
| 618 | ); |
| 619 | return McpHttpServer.McpClientAuthenticator.of({ |
| 620 | authenticate: Effect.fn("McpHttpServer.McpClientAuthenticator.authenticate")( |
| 621 | function (request) { |
| 622 | return environmentAuth.authenticateMcpClient(request).pipe( |
| 623 | Effect.flatMap((client) => |
| 624 | Clock.currentTimeMillis.pipe( |
| 625 | Effect.map((issuedAt): McpInvocationContext.McpInvocationScope => ({ |
| 626 | environmentId, |
| 627 | requestNamespace: `client:${client.sessionId}`, |
| 628 | thread: undefined, |
| 629 | client: { |
| 630 | sessionId: client.sessionId, |
| 631 | label: client.label, |
| 632 | access: client.access, |
| 633 | linked: client.peerLink, |
| 634 | linkExpiresAt: client.linkExpiresAt, |
| 635 | ...(client.peerLink ? {} : { hostedAppUrl }), |
| 636 | }, |
| 637 | capabilities: new Set<McpInvocationContext.McpCapability>([ |
| 638 | "orchestration", |
| 639 | "worktree", |
| 640 | "pull-requests", |
| 641 | ]), |
| 642 | issuedAt, |
| 643 | })), |
| 644 | ), |
| 645 | ), |
| 646 | Effect.catch((error) => |
| 647 | (EnvironmentAuth.isServerAuthCredentialError(error) |
| 648 | ? Effect.void |
| 649 | : Effect.logWarning("MCP client authentication failed.", { cause: error }) |
| 650 | ).pipe(Effect.as(undefined)), |
| 651 | ), |
| 652 | ); |
| 653 | }, |
| 654 | ), |
| 655 | }); |
| 656 | }), |
| 657 | ); |