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