Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EnvironmentAuth.ts

1,315 lines47.6 KB

1import {
2 AuthAccessTokenType,
3 AuthAccessWriteScope,
4 AuthAdministrativeScopes,
5 AuthOrchestrationOperateScope,
6 AuthOrchestrationReadScope,
7 AuthStandardClientScopes,
8 type AuthAccessTokenResult,
9 type AuthBrowserSessionResult,
10 type AuthClientMetadata,
11 type AuthClientSession,
12 type AuthCreatePairingCredentialInput,
13 type AuthEnvironmentScope,
14 type AuthMcpClientAccess,
15 type AuthPairingLink,
16 type AuthPairingCredentialResult,
17 type AuthSessionId,
18 type AuthSessionState,
19 authScopeResponse,
20 type ServerAuthDescriptor,
21 type ServerAuthSessionMethod,
22 type AuthWebSocketTicketResult,
23 DpopFailureReason,
24 type DpopFailureReason as DpopFailureReasonType,
25} from "@t3tools/contracts";
26import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
27import * as Context from "effect/Context";
28import * as Crypto from "effect/Crypto";
29import * as DateTime from "effect/DateTime";
30import * as Duration from "effect/Duration";
31import * as Effect from "effect/Effect";
32import * as Layer from "effect/Layer";
33import * as Option from "effect/Option";
34import * as Schema from "effect/Schema";
35import * as HttpServerRequest from "effect/http/HttpServerRequest";
36​
37import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
38import * as ServerConfig from "../config.ts";
39import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
40import * as PairingGrantStore from "./PairingGrantStore.ts";
41import * as ServerSecretStore from "./ServerSecretStore.ts";
42import * as SessionStore from "./SessionStore.ts";
43import { REUSABLE_DEV_SESSION_EXPIRES_AT, resolveReusableDevAuth } from "./ReusableDevAuth.ts";
44import { verifyRequestDpopProof } from "./dpop.ts";
45import * as SqlitePersistence from "../persistence/Sqlite.ts";
46​
47const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
48export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
49​
50export interface IssuedPairingLink {
51 readonly id: string;
52 readonly credential: string;
53 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
54 readonly subject: string;
55 readonly label?: string;
56 readonly createdAt: DateTime.Utc;
57 readonly expiresAt: DateTime.Utc;
59​
60export interface IssuedBearerSession {
61 readonly sessionId: AuthSessionId;
62 readonly token: string;
63 readonly method: "bearer-access-token";
64 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
65 readonly subject: string;
66 readonly client: AuthClientMetadata;
67 readonly expiresAt: DateTime.Utc;
69​
70/**
71 * Sessions an MCP client (an agent T3 Code did not launch) obtains through
72 * OAuth. They are accepted only by `/mcp`, where every action is capped by the
73 * access the user approved; the HTTP API and WebSocket reject them so an agent
74 * token cannot reach the full RPC surface around that cap.
75 *
76 * A read-only grant holds `orchestration:read` alone. Any other grant also
77 * holds `orchestration:operate` and carries its runtime-mode ceiling.
78 */
79const MCP_CLIENT_SUBJECT = "mcp-client";
80const MCP_CLIENT_SESSION_TTL = Duration.days(30);
81​
82export const mcpClientScopes = (
83 access: AuthMcpClientAccess,
84): ReadonlyArray<AuthEnvironmentScope> =>
85 access === "read-only"
86 ? [AuthOrchestrationReadScope]
87 : [AuthOrchestrationReadScope, AuthOrchestrationOperateScope];
88​
89export interface McpClientSession {
90 readonly sessionId: AuthSessionId;
91 readonly label: string;
92 readonly access: AuthMcpClientAccess;
94​
95export interface AuthenticatedSession {
96 readonly sessionId: AuthSessionId;
97 readonly subject: string;
98 readonly method: ServerAuthSessionMethod;
99 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
100 readonly proofKeyThumbprint?: string;
101 readonly expiresAt?: DateTime.DateTime;
103​
104const serverAuthInternalErrorContext = {
105 cause: Schema.Defect(),
106};
107​
108export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedError<ServerAuthBootstrapCredentialValidationError>()(
109 "ServerAuthBootstrapCredentialValidationError",
110 {
111 ...serverAuthInternalErrorContext,
112 },
113) {
114 override get message(): string {
115 return "Failed to validate bootstrap credential.";
116 }
118​
119export class ServerAuthSessionCredentialValidationError extends Schema.TaggedError<ServerAuthSessionCredentialValidationError>()(
120 "ServerAuthSessionCredentialValidationError",
121 {
122 ...serverAuthInternalErrorContext,
123 },
124) {
125 override get message(): string {
126 return "Failed to validate session credential.";
127 }
129​
130export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedError<ServerAuthAuthenticatedSessionIssueError>()(
131 "ServerAuthAuthenticatedSessionIssueError",
132 {
133 ...serverAuthInternalErrorContext,
134 },
135) {
136 override get message(): string {
137 return "Failed to issue authenticated session.";
138 }
140​
141export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedError<ServerAuthAuthenticatedAccessTokenIssueError>()(
142 "ServerAuthAuthenticatedAccessTokenIssueError",
143 {
144 ...serverAuthInternalErrorContext,
145 },
146) {
147 override get message(): string {
148 return "Failed to issue authenticated access token.";
149 }
151​
152export class ServerAuthPairingLinkCreationError extends Schema.TaggedError<ServerAuthPairingLinkCreationError>()(
153 "ServerAuthPairingLinkCreationError",
154 {
155 ...serverAuthInternalErrorContext,
156 },
157) {
158 override get message(): string {
159 return "Failed to create pairing link.";
160 }
162​
163export class ServerAuthPairingLinksListError extends Schema.TaggedError<ServerAuthPairingLinksListError>()(
164 "ServerAuthPairingLinksListError",
165 {
166 ...serverAuthInternalErrorContext,
167 },
168) {
169 override get message(): string {
170 return "Failed to list pairing links.";
171 }
173​
174export class ServerAuthPairingLinkRevocationError extends Schema.TaggedError<ServerAuthPairingLinkRevocationError>()(
175 "ServerAuthPairingLinkRevocationError",
176 {
177 ...serverAuthInternalErrorContext,
178 },
179) {
180 override get message(): string {
181 return "Failed to revoke pairing link.";
182 }
184​
185export class ServerAuthSessionTokenIssueError extends Schema.TaggedError<ServerAuthSessionTokenIssueError>()(
186 "ServerAuthSessionTokenIssueError",
187 {
188 ...serverAuthInternalErrorContext,
189 },
190) {
191 override get message(): string {
192 return "Failed to issue session token.";
193 }
195​
196export class ServerAuthSessionsListError extends Schema.TaggedError<ServerAuthSessionsListError>()(
197 "ServerAuthSessionsListError",
198 {
199 ...serverAuthInternalErrorContext,
200 },
201) {
202 override get message(): string {
203 return "Failed to list sessions.";
204 }
206​
207export class ServerAuthSessionRevocationError extends Schema.TaggedError<ServerAuthSessionRevocationError>()(
208 "ServerAuthSessionRevocationError",
209 {
210 ...serverAuthInternalErrorContext,
211 },
212) {
213 override get message(): string {
214 return "Failed to revoke session.";
215 }
217​
218export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedError<ServerAuthOtherSessionsRevocationError>()(
219 "ServerAuthOtherSessionsRevocationError",
220 {
221 ...serverAuthInternalErrorContext,
222 },
223) {
224 override get message(): string {
225 return "Failed to revoke other sessions.";
226 }
228​
229export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedError<ServerAuthWebSocketTokenIssueError>()(
230 "ServerAuthWebSocketTokenIssueError",
231 {
232 ...serverAuthInternalErrorContext,
233 },
234) {
235 override get message(): string {
236 return "Failed to issue websocket token.";
237 }
239​
240export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedError<ServerAuthDpopReplayStateRecordError>()(
241 "ServerAuthDpopReplayStateRecordError",
242 {
243 ...serverAuthInternalErrorContext,
244 },
245) {
246 override get message(): string {
247 return "Failed to record DPoP proof replay state.";
248 }
250​
251export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedError<ServerAuthDpopReplayKeyCalculationError>()(
252 "ServerAuthDpopReplayKeyCalculationError",
253 {
254 ...serverAuthInternalErrorContext,
255 },
256) {
257 override get message(): string {
258 return "Failed to calculate DPoP replay key.";
259 }
261​
262export class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedError<ServerAuthLinkedCloudAccountVerificationError>()(
263 "ServerAuthLinkedCloudAccountVerificationError",
264 {
265 ...serverAuthInternalErrorContext,
266 },
267) {
268 override get message(): string {
269 return "Could not verify the linked cloud account.";
270 }
272​
273export class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedError<ServerAuthLinkedCloudAccountReadError>()(
274 "ServerAuthLinkedCloudAccountReadError",
275 {
276 ...serverAuthInternalErrorContext,
277 },
278) {
279 override get message(): string {
280 return "Could not read the linked cloud account.";
281 }
283​
284export class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedError<ServerAuthLinkedCloudAccountMissingError>()(
285 "ServerAuthLinkedCloudAccountMissingError",
286 {},
287) {
288 override get message(): string {
289 return "Cloud linked user is not installed for this environment.";
290 }
292​
293export class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedError<ServerAuthCloudLinkJwtSigningError>()(
294 "ServerAuthCloudLinkJwtSigningError",
295 {
296 ...serverAuthInternalErrorContext,
297 },
298) {
299 override get message(): string {
300 return "Failed to sign cloud link JWT.";
301 }
303​
304export class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedError<ServerAuthCloudMintPublicKeyMissingError>()(
305 "ServerAuthCloudMintPublicKeyMissingError",
306 {},
307) {
308 override get message(): string {
309 return "Cloud mint public key is not installed for this environment.";
310 }
312​
313export class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedError<ServerAuthCloudRelayIssuerMissingError>()(
314 "ServerAuthCloudRelayIssuerMissingError",
315 {},
316) {
317 override get message(): string {
318 return "Cloud relay issuer is not installed for this environment.";
319 }
321​
322export class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedError<ServerAuthCloudHealthJwtSigningError>()(
323 "ServerAuthCloudHealthJwtSigningError",
324 {
325 ...serverAuthInternalErrorContext,
326 },
327) {
328 override get message(): string {
329 return "Failed to sign cloud health JWT.";
330 }
332​
333export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedError<ServerAuthCloudMintJwtSigningError>()(
334 "ServerAuthCloudMintJwtSigningError",
335 {
336 ...serverAuthInternalErrorContext,
337 },
338) {
339 override get message(): string {
340 return "Failed to sign cloud mint JWT.";
341 }
343​
344export const ServerAuthInternalError = Schema.Union([
345 ServerAuthBootstrapCredentialValidationError,
346 ServerAuthSessionCredentialValidationError,
347 ServerAuthAuthenticatedSessionIssueError,
348 ServerAuthAuthenticatedAccessTokenIssueError,
349 ServerAuthPairingLinkCreationError,
350 ServerAuthPairingLinksListError,
351 ServerAuthPairingLinkRevocationError,
352 ServerAuthSessionTokenIssueError,
353 ServerAuthSessionsListError,
354 ServerAuthSessionRevocationError,
355 ServerAuthOtherSessionsRevocationError,
356 ServerAuthWebSocketTokenIssueError,
357 ServerAuthDpopReplayStateRecordError,
358 ServerAuthDpopReplayKeyCalculationError,
359 ServerAuthLinkedCloudAccountVerificationError,
360 ServerAuthLinkedCloudAccountReadError,
361 ServerAuthLinkedCloudAccountMissingError,
362 ServerAuthCloudLinkJwtSigningError,
363 ServerAuthCloudMintPublicKeyMissingError,
364 ServerAuthCloudRelayIssuerMissingError,
365 ServerAuthCloudHealthJwtSigningError,
366 ServerAuthCloudMintJwtSigningError,
367]);
368export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
369export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
370​
371export class ServerAuthMissingCredentialError extends Schema.TaggedError<ServerAuthMissingCredentialError>()(
372 "ServerAuthMissingCredentialError",
373 {},
374) {
375 override get message(): string {
376 return "Server authentication credential is missing.";
377 }
379​
380export class ServerAuthInvalidCredentialError extends Schema.TaggedError<ServerAuthInvalidCredentialError>()(
381 "ServerAuthInvalidCredentialError",
382 {
383 diagnostic: Schema.optional(Schema.String),
384 dpopFailureReason: Schema.optionalKey(DpopFailureReason),
385 cause: Schema.optional(Schema.Defect()),
386 },
387) {
388 override get message(): string {
389 return "Server authentication credential is invalid.";
390 }
392​
393export const ServerAuthCredentialError = Schema.Union([
394 ServerAuthMissingCredentialError,
395 ServerAuthInvalidCredentialError,
396]);
397export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
398export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
399export const serverAuthCredentialReason = (
400 error: ServerAuthCredentialError,
401): "missing_credential" | "invalid_credential" =>
402 error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
403​
404export const serverAuthDpopFailureReason = (
405 error: ServerAuthCredentialError,
406): DpopFailureReasonType | undefined =>
407 error._tag === "ServerAuthInvalidCredentialError" ? error.dpopFailureReason : undefined;
408​
409export class ServerAuthInvalidScopeError extends Schema.TaggedError<ServerAuthInvalidScopeError>()(
410 "ServerAuthInvalidScopeError",
411 {},
412) {
413 override get message(): string {
414 return "The requested authentication scope is invalid.";
415 }
417​
418export class ServerAuthScopeNotGrantedError extends Schema.TaggedError<ServerAuthScopeNotGrantedError>()(
419 "ServerAuthScopeNotGrantedError",
420 {},
421) {
422 override get message(): string {
423 return "The requested authentication scope was not granted.";
424 }
426​
427export const ServerAuthInvalidRequestError = Schema.Union([
428 ServerAuthInvalidScopeError,
429 ServerAuthScopeNotGrantedError,
430]);
431export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
432export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
433export const serverAuthInvalidRequestReason = (
434 error: ServerAuthInvalidRequestError,
435): "invalid_scope" | "scope_not_granted" =>
436 error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
437​
438export class ServerAuthMcpApprovalCodeError extends Schema.TaggedError<ServerAuthMcpApprovalCodeError>()(
439 "ServerAuthMcpApprovalCodeError",
440 { reason: Schema.Literals(["unknown_or_used", "not_a_pairing_code", "insufficient_scope"]) },
441) {
442 override get message(): string {
443 return this.reason === "insufficient_scope"
444 ? "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."
445 : this.reason === "not_a_pairing_code"
446 ? "That is not a one-time pairing code."
447 : "That pairing code is unknown, expired, or already used.";
448 }
450​
451export class ServerAuthForbiddenOperationError extends Schema.TaggedError<ServerAuthForbiddenOperationError>()(
452 "ServerAuthForbiddenOperationError",
453 {},
454) {
455 override get message(): string {
456 return "The current authentication session cannot revoke itself.";
457 }
459​
460export class EnvironmentAuth extends Context.Service<
461 EnvironmentAuth,
462 {
463 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
464 readonly getSessionState: (
465 request: HttpServerRequest.HttpServerRequest,
466 ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
467 readonly createBrowserSession: (
468 credential: string,
469 requestMetadata: AuthClientMetadata,
470 previousSessionToken?: string,
471 ) => Effect.Effect<
472 {
473 readonly response: AuthBrowserSessionResult;
474 readonly sessionToken: string;
475 readonly cookieName?: string;
476 readonly expireNormalCookie?: boolean;
477 },
478 ServerAuthInvalidCredentialError | ServerAuthInternalError
479 >;
480 readonly exchangeBootstrapCredentialForAccessToken: (
481 credential: string,
482 requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
483 requestMetadata: AuthClientMetadata,
484 input?: {
485 readonly proofKeyThumbprint?: string;
486 },
487 ) => Effect.Effect<
488 AuthAccessTokenResult,
489 ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
490 >;
491 readonly createPairingLink: (input?: {
492 readonly ttl?: Duration.Duration;
493 readonly label?: string;
494 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
495 readonly subject?: string;
496 readonly proofKeyThumbprint?: string;
497 readonly purpose?: "startup";
498 }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
499 readonly issuePairingCredential: (
500 input?: AuthCreatePairingCredentialInput,
501 ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
502 readonly issueStartupPairingCredential: () => Effect.Effect<
503 AuthPairingCredentialResult,
504 ServerAuthInternalError
505 >;
506 readonly listPairingLinks: (input?: {
507 readonly excludeSubjects?: ReadonlyArray<string>;
508 }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
509 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
510 readonly issueSession: (input?: {
511 readonly ttl?: Duration.Duration;
512 readonly subject?: string;
513 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
514 readonly label?: string;
515 }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
516 readonly listSessions: () => Effect.Effect<
517 ReadonlyArray<AuthClientSession>,
518 ServerAuthInternalError
519 >;
520 readonly revokeSession: (
521 sessionId: AuthSessionId,
522 ) => Effect.Effect<boolean, ServerAuthInternalError>;
523 readonly revokeOtherSessionsExcept: (
524 sessionId: AuthSessionId,
525 ) => Effect.Effect<number, ServerAuthInternalError>;
526 readonly listClientSessions: (
527 currentSessionId: AuthSessionId,
528 ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
529 readonly revokeClientSession: (
530 currentSessionId: AuthSessionId,
531 targetSessionId: AuthSessionId,
532 ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
533 readonly revokeOtherClientSessions: (
534 currentSessionId: AuthSessionId,
535 ) => Effect.Effect<number, ServerAuthInternalError>;
536 readonly authenticateHttpRequest: (
537 request: HttpServerRequest.HttpServerRequest,
538 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
539 readonly authenticateWebSocketUpgrade: (
540 request: HttpServerRequest.HttpServerRequest,
541 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
542 readonly issueWebSocketTicket: (
543 session: Pick<AuthenticatedSession, "sessionId">,
544 ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
545 readonly issueStartupPairingUrl: (
546 baseUrl: string,
547 ) => Effect.Effect<string, ServerAuthInternalError>;
548 /** Only bearer `mcp-client` sessions; never cookies or proof-bound tokens. */
549 readonly authenticateMcpClient: (
550 request: HttpServerRequest.HttpServerRequest,
551 ) => Effect.Effect<McpClientSession, ServerAuthCredentialError | ServerAuthInternalError>;
552 readonly issueMcpClientSession: (input: {
553 readonly label: string;
554 readonly access: AuthMcpClientAccess;
555 readonly client: AuthClientMetadata;
556 }) => Effect.Effect<
557 { readonly token: string; readonly expiresAt: DateTime.DateTime },
558 ServerAuthInternalError
559 >;
560 /**
561 * Spends a one-time pairing code as approval for an MCP client with the
562 * given access; the code must hold every scope that access grants.
563 * Proof-bound codes (T3 Connect) are refused without being spent, and
564 * desktop bootstrap grants never qualify.
565 */
566 readonly consumeMcpApprovalCode: (
567 code: string,
568 access: AuthMcpClientAccess,
569 ) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
570 /** A browser cookie session only; a bearer header never counts as one. */
571 readonly authenticateBrowserSession: (
572 request: HttpServerRequest.HttpServerRequest,
573 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
574 }
575>()("t3/auth/EnvironmentAuth") {}
576​
577type BootstrapExchangeResult = {
578 readonly response: AuthBrowserSessionResult;
579 readonly sessionToken: string;
580 readonly cookieName?: string;
581 readonly expireNormalCookie?: boolean;
582};
583​
584const AUTHORIZATION_PREFIX = "Bearer ";
585const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
586const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
587​
588const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
589 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
590 const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
591 if (leftCanManage !== rightCanManage) {
592 return leftCanManage ? -1 : 1;
593 }
594 if (left.connected !== right.connected) {
595 return left.connected ? -1 : 1;
596 }
597 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
598};
599​
600export function toBootstrapExchangeError(
601 cause: PairingGrantStore.BootstrapCredentialError,
602): ServerAuthInvalidCredentialError | ServerAuthInternalError {
603 if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
604 return new ServerAuthBootstrapCredentialValidationError({ cause });
605 }
606​
607 return new ServerAuthInvalidCredentialError({
608 cause,
609 });
611​
612const rejectMcpClientAudience = <S extends { readonly subject: string }>(session: S) =>
613 session.subject === MCP_CLIENT_SUBJECT
614 ? Effect.fail(
615 new ServerAuthInvalidCredentialError({
616 diagnostic: "MCP client sessions are only accepted by the MCP endpoint.",
617 }),
618 ).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp.")))
619 : Effect.succeed(session);
620​
621const mapSessionVerificationErrors = <A, R>(
622 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
623): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
624 effect.pipe(
625 Effect.mapError((cause) =>
626 SessionStore.isSessionCredentialInvalidError(cause)
627 ? new ServerAuthInvalidCredentialError({ cause })
628 : new ServerAuthSessionCredentialValidationError({ cause }),
629 ),
630 );
631​
632function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
633 const header = request.headers["authorization"];
634 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
635 return null;
636 }
637 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
638 return token.length > 0 ? token : null;
640​
641function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {
642 const header = request.headers["authorization"];
643 if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {
644 return null;
645 }
646 const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();
647 return token.length > 0 ? token : null;
649​
650export function selectRequestCredential(
651 request: HttpServerRequest.HttpServerRequest,
652 cookieName: string,
653 legacyCookieName: string | undefined,
654) {
655 const cookieToken = request.cookies[cookieName];
656 if (cookieToken !== undefined) {
657 return { token: cookieToken, source: "cookie" } as const;
658 }
659​
660 const bearerToken = parseBearerToken(request);
661 if (bearerToken !== null) {
662 return { token: bearerToken, source: "bearer" } as const;
663 }
664​
665 const dpopToken = parseDpopToken(request);
666 if (dpopToken !== null) {
667 return { token: dpopToken, source: "dpop" } as const;
668 }
669​
670 const legacyToken = legacyCookieName ? request.cookies[legacyCookieName] : undefined;
671 if (legacyToken !== undefined) {
672 return { token: legacyToken, source: "legacy-cookie" } as const;
673 }
674​
675 return undefined;
677​
678/** @public Service construction is part of the canonical Effect module API. */
679export const make = Effect.gen(function* () {
680 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
681 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
682 const sessions = yield* SessionStore.SessionStore;
683 const secretStore = yield* ServerSecretStore.ServerSecretStore;
684 const crypto = yield* Crypto.Crypto;
685 const descriptor = yield* policy.getDescriptor();
686 const config = yield* ServerConfig.ServerConfig;
687 const devAuth = resolveReusableDevAuth(config);
688​
689 const authenticateToken = (
690 token: string,
691 ): Effect.Effect<
692 AuthenticatedSession,
693 ServerAuthInvalidCredentialError | ServerAuthInternalError
694 > =>
695 sessions.verify(token).pipe(
696 Effect.tapError((cause) =>
697 SessionStore.isSessionCredentialInvalidError(cause)
698 ? Effect.logWarning("Rejected authenticated session credential.").pipe(
699 Effect.annotateLogs({
700 reason: cause.message,
701 }),
702 )
703 : Effect.void,
704 ),
705 mapSessionVerificationErrors,
706 Effect.flatMap(rejectMcpClientAudience),
707 Effect.map((session) => ({
708 sessionId: session.sessionId,
709 subject: session.subject,
710 method: session.method,
711 scopes: session.scopes,
712 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
713 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
714 })),
715 );
716​
717 const authenticateRequest = (
718 request: HttpServerRequest.HttpServerRequest,
719 ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
720 const selectedCredential = selectRequestCredential(
721 request,
722 sessions.cookieName,
723 sessions.legacyCookieName,
724 );
725 const dpopToken = parseDpopToken(request);
726 const hasAuthorization = request.headers.authorization !== undefined;
727 const devCookieToken = devAuth ? request.cookies[devAuth.cookieName] : undefined;
728 const credential =
729 selectedCredential ??
730 (!hasAuthorization && devCookieToken !== undefined
731 ? { token: devCookieToken, source: "dev-cookie" as const }
732 : undefined);
733 if (!credential?.token) {
734 return Effect.fail(new ServerAuthMissingCredentialError({}));
735 }
736 return authenticateToken(credential.token).pipe(
737 Effect.flatMap((session) => {
738 if (session.proofKeyThumbprint) {
739 if (!dpopToken || dpopToken !== credential.token) {
740 return Effect.fail(
741 new ServerAuthInvalidCredentialError({
742 diagnostic: "DPoP-bound access token requires DPoP authorization.",
743 dpopFailureReason: "invalid_proof",
744 }),
745 );
746 }
747 return verifyRequestDpopProof({
748 request,
749 expectedThumbprint: session.proofKeyThumbprint,
750 expectedAccessToken: dpopToken,
751 }).pipe(
752 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
753 Effect.provideService(Crypto.Crypto, crypto),
754 Effect.as(session),
755 );
756 }
757 if (dpopToken) {
758 return Effect.fail(
759 new ServerAuthInvalidCredentialError({
760 diagnostic: "DPoP authorization requires a proof-bound access token.",
761 dpopFailureReason: "invalid_proof",
762 }),
763 );
764 }
765 return Effect.succeed(session);
766 }),
767 );
768 };
769​
770 const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
771 authenticateRequest(request).pipe(
772 Effect.map(
773 (session) =>
774 ({
775 authenticated: true,
776 auth: descriptor,
777 ...authScopeResponse(session.scopes),
778 sessionMethod: session.method,
779 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
780 }) satisfies AuthSessionState,
781 ),
782 Effect.catchIf(isServerAuthCredentialError, () =>
783 Effect.succeed({
784 authenticated: false,
785 auth: descriptor,
786 } satisfies AuthSessionState),
787 ),
788 Effect.withSpan("EnvironmentAuth.getSessionState"),
789 );
790​
791 const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn(
792 "EnvironmentAuth.createBrowserSession",
793 )(function* (credential, requestMetadata, previousSessionToken) {
794 if (devAuth?.matches(credential)) {
795 return yield* sessions.verify(credential).pipe(
796 mapSessionVerificationErrors,
797 Effect.flatMap((session) =>
798 DateTime.now.pipe(
799 Effect.map(
800 (now) =>
801 ({
802 response: {
803 authenticated: true,
804 ...authScopeResponse(session.scopes),
805 sessionMethod: session.method,
806 expiresAt: DateTime.toUtc(DateTime.add(now, { days: 30 })),
807 } satisfies AuthBrowserSessionResult,
808 sessionToken: credential,
809 cookieName: devAuth.cookieName,
810 expireNormalCookie: true,
811 }) satisfies BootstrapExchangeResult,
812 ),
813 ),
814 ),
815 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
816 );
817 }
818 const previousSession =
819 previousSessionToken === undefined
820 ? undefined
821 : yield* sessions.verify(previousSessionToken).pipe(
822 Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.void),
823 Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })),
824 );
825 const grant = yield* bootstrapCredentials
826 .consume(credential)
827 .pipe(Effect.mapError(toBootstrapExchangeError));
828 const session = yield* sessions
829 .issue({
830 method: "browser-session-cookie",
831 subject: grant.subject,
832 scopes: grant.scopes,
833 ...(previousSession?.method === "browser-session-cookie"
834 ? { replaceSessionId: previousSession.sessionId }
835 : {}),
836 client: {
837 ...requestMetadata,
838 ...(grant.label ? { label: grant.label } : {}),
839 },
840 })
841 .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })));
842 return {
843 response: {
844 authenticated: true,
845 ...authScopeResponse(session.scopes),
846 sessionMethod: session.method,
847 expiresAt: DateTime.toUtc(session.expiresAt),
848 } satisfies AuthBrowserSessionResult,
849 sessionToken: session.token,
850 } satisfies BootstrapExchangeResult;
851 });
852​
853 type ResolvedBootstrapGrant = Pick<
854 PairingGrantStore.BootstrapGrant,
855 "scopes" | "subject" | "label"
856 > & {
857 readonly method: PairingGrantStore.BootstrapGrant["method"] | "reusable-dev-token";
858 };
859 const resolveBootstrapGrant = (
860 credential: string,
861 input?: {
862 readonly proofKeyThumbprint?: string;
863 readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
864 },
865 ): Effect.Effect<
866 ResolvedBootstrapGrant,
867 ServerAuthInvalidCredentialError | ServerAuthInternalError | ServerAuthScopeNotGrantedError
868 > => {
869 if (!devAuth?.matches(credential)) {
870 return bootstrapCredentials
871 .consume(credential, input)
872 .pipe(
873 Effect.mapError((cause) =>
874 cause._tag === "BootstrapCredentialScopeNotGrantedError"
875 ? new ServerAuthScopeNotGrantedError({})
876 : toBootstrapExchangeError(cause),
877 ),
878 );
879 }
880 return sessions.verify(credential).pipe(
881 mapSessionVerificationErrors,
882 Effect.map(
883 (session) =>
884 ({
885 method: "reusable-dev-token",
886 scopes: session.scopes,
887 subject: "reusable-dev-token-child",
888 }) satisfies ResolvedBootstrapGrant,
889 ),
890 );
891 };
892​
893 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
894 (credential, requestedScopes, requestMetadata, input) => {
895 return resolveBootstrapGrant(credential, {
896 ...input,
897 ...(requestedScopes !== undefined ? { requestedScopes } : {}),
898 }).pipe(
899 Effect.flatMap((grant) =>
900 Effect.gen(function* () {
901 const grantedScopes =
902 requestedScopes === undefined
903 ? grant.scopes
904 : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope));
905 if (grantedScopes.length === 0) {
906 return yield* new ServerAuthScopeNotGrantedError({});
907 }
908 return yield* sessions
909 .issue({
910 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
911 subject: grant.subject,
912 scopes: grantedScopes,
913 ...(input?.proofKeyThumbprint
914 ? {
915 proofKeyThumbprint: input.proofKeyThumbprint,
916 ttl: Duration.hours(1),
917 }
918 : {}),
919 // Desktop restarts forget the previous bearer token. Replace
920 // its session, including stale entries left by older versions.
921 replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap",
922 client: {
923 ...requestMetadata,
924 ...(grant.label ? { label: grant.label } : {}),
925 },
926 })
927 .pipe(
928 Effect.mapError(
929 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
930 ),
931 );
932 }),
933 ),
934 Effect.flatMap((session) =>
935 DateTime.now.pipe(
936 Effect.map(
937 (now) =>
938 ({
939 access_token: session.token,
940 issued_token_type: AuthAccessTokenType,
941 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
942 expires_in: Math.max(
943 0,
944 Math.floor(
945 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
946 ),
947 ),
948 scope: encodeOAuthScope(session.scopes),
949 }) satisfies AuthAccessTokenResult,
950 ),
951 ),
952 ),
953 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
954 );
955 };
956​
957 const issuePairingCredentialForSubject = (input: {
958 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
959 readonly subject: string;
960 readonly label?: string;
961 readonly purpose?: "startup";
962 }) =>
963 createPairingLink({
964 scopes: input.scopes,
965 subject: input.subject,
966 ...(input.label ? { label: input.label } : {}),
967 ...(input.purpose ? { purpose: input.purpose } : {}),
968 }).pipe(
969 Effect.map(
970 (issued) =>
971 ({
972 id: issued.id,
973 credential: issued.credential,
974 ...(issued.label ? { label: issued.label } : {}),
975 expiresAt: issued.expiresAt,
976 }) satisfies AuthPairingCredentialResult,
977 ),
978 );
979​
980 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
981 "EnvironmentAuth.createPairingLink",
982 )(
983 function* (input) {
984 const createdAt = yield* DateTime.now;
985 const issued = yield* bootstrapCredentials.issueOneTimeToken({
986 scopes: input?.scopes ?? AuthStandardClientScopes,
987 subject: input?.subject ?? "one-time-token",
988 ...(input?.ttl ? { ttl: input.ttl } : {}),
989 ...(input?.label ? { label: input.label } : {}),
990 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
991 ...(input?.purpose ? { purpose: input.purpose } : {}),
992 });
993 return {
994 id: issued.id,
995 credential: issued.credential,
996 scopes: input?.scopes ?? AuthStandardClientScopes,
997 subject: input?.subject ?? "one-time-token",
998 ...(issued.label ? { label: issued.label } : {}),
999 createdAt: DateTime.toUtc(createdAt),
1000 expiresAt: DateTime.toUtc(issued.expiresAt),
1001 } satisfies IssuedPairingLink;
1002 },
1003 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
1004 );
1005​
1006 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
1007 bootstrapCredentials.listActive().pipe(
1008 Effect.map((pairingLinks) => {
1009 const excludedSubjects = input?.excludeSubjects ?? [
1010 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1011 ];
1012 return pairingLinks
1013 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
1014 .map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
1015 .toSorted(
1016 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
1017 );
1018 }),
1019 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
1020 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
1021 );
1022​
1023 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
1024 bootstrapCredentials.revoke(id).pipe(
1025 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
1026 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
1027 );
1028​
1029 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
1030 sessions
1031 .issue({
1032 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1033 method: "bearer-access-token",
1034 scopes: input?.scopes ?? AuthAdministrativeScopes,
1035 client: {
1036 ...(input?.label ? { label: input.label } : {}),
1037 deviceType: "bot",
1038 },
1039 ...(input?.ttl ? { ttl: input.ttl } : {}),
1040 })
1041 .pipe(
1042 Effect.map(
1043 (issued) =>
1044 ({
1045 sessionId: issued.sessionId,
1046 token: issued.token,
1047 method: "bearer-access-token",
1048 scopes: issued.scopes,
1049 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1050 client: issued.client,
1051 expiresAt: DateTime.toUtc(issued.expiresAt),
1052 }) satisfies IssuedBearerSession,
1053 ),
1054 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1055 Effect.withSpan("EnvironmentAuth.issueSession"),
1056 );
1057​
1058 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
1059 sessions.listActive().pipe(
1060 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
1061 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
1062 Effect.withSpan("EnvironmentAuth.listSessions"),
1063 );
1064​
1065 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
1066 sessions.revoke(sessionId).pipe(
1067 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
1068 Effect.withSpan("EnvironmentAuth.revokeSession"),
1069 );
1070​
1071 const revokeOtherSessionsExcept: EnvironmentAuth["Service"]["revokeOtherSessionsExcept"] = (
1072 sessionId,
1073 ) =>
1074 sessions.revokeAllExcept(sessionId).pipe(
1075 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
1076 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
1077 );
1078​
1079 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
1080 issuePairingCredentialForSubject({
1081 scopes: input?.scopes ?? AuthStandardClientScopes,
1082 subject: "one-time-token",
1083 ...(input?.label ? { label: input.label } : {}),
1084 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
1085​
1086 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
1087 () => {
1088 const fallback = issuePairingCredentialForSubject({
1089 scopes: AuthAdministrativeScopes,
1090 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1091 purpose: "startup",
1092 });
1093 if (!devAuth) {
1094 return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
1096 return sessions.verify(devAuth.credential).pipe(
1097 Effect.map(
1098 (session) =>
1099 ({
1100 id: session.sessionId,
1101 credential: devAuth.credential,
1102 label: "Reusable dev token",
1103 expiresAt: DateTime.toUtc(session.expiresAt ?? REUSABLE_DEV_SESSION_EXPIRES_AT),
1104 }) satisfies AuthPairingCredentialResult,
1105 ),
1106 Effect.catch((cause) =>
1107 SessionStore.isSessionCredentialInvalidError(cause)
1108 ? fallback
1109 : Effect.fail(new ServerAuthPairingLinkCreationError({ cause })),
1110 ),
1111 Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"),
1112 );
1113 };
1114​
1115 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
1116 listSessions().pipe(
1117 Effect.map((clientSessions) =>
1118 clientSessions.map((clientSession): AuthClientSession => ({
1119 ...clientSession,
1120 ...authScopeResponse(clientSession.scopes),
1121 current: clientSession.sessionId === currentSessionId,
1122 })),
1123 ),
1124 Effect.withSpan("EnvironmentAuth.listClientSessions"),
1125 );
1126​
1127 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
1128 "EnvironmentAuth.revokeClientSession",
1129 )(function* (currentSessionId, targetSessionId) {
1130 if (currentSessionId === targetSessionId) {
1131 return yield* new ServerAuthForbiddenOperationError({});
1133 return yield* revokeSession(targetSessionId);
1134 });
1135​
1136 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
1137 currentSessionId,
1138 ) =>
1139 revokeOtherSessionsExcept(currentSessionId).pipe(
1140 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
1141 );
1142​
1143 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
1144 issueStartupPairingCredential().pipe(
1145 Effect.map((issued) => {
1146 const url = new URL(baseUrl);
1147 url.pathname = "/pair";
1148 url.searchParams.delete("token");
1149 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
1150 return url.toString();
1151 }),
1152 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
1153 );
1154​
1155 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
1156 sessions.issueWebSocketToken(session.sessionId).pipe(
1157 Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1158 Effect.map(
1159 (issued) =>
1160 ({
1161 ticket: issued.token,
1162 expiresAt: DateTime.toUtc(issued.expiresAt),
1163 }) satisfies AuthWebSocketTicketResult,
1164 ),
1165 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1166 );
1167​
1168 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
1169 request,
1170 ) =>
1171 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
1172​
1173 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
1174 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
1175 const requestUrl = HttpServerRequest.toURL(request);
1176 if (Option.isSome(requestUrl)) {
1177 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
1178 if (websocketTicket && websocketTicket.trim().length > 0) {
1179 return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
1180 mapSessionVerificationErrors,
1181 Effect.flatMap(rejectMcpClientAudience),
1182 Effect.map((session) => ({
1183 sessionId: session.sessionId,
1184 subject: session.subject,
1185 method: session.method,
1186 scopes: session.scopes,
1187 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1188 })),
1189 );
1192​
1193 return yield* authenticateRequest(request);
1194 });
1195​
1196 const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
1197 const token = parseBearerToken(request);
1198 if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
1199 return sessions.verify(token).pipe(
1200 mapSessionVerificationErrors,
1201 Effect.flatMap((session) =>
1202 session.subject === MCP_CLIENT_SUBJECT && session.method === "bearer-access-token"
1203 ? Effect.succeed({
1204 sessionId: session.sessionId,
1205 label: session.client.label ?? "MCP client",
1206 access: session.scopes.includes(AuthOrchestrationOperateScope)
1207 ? (session.runtimeModeCeiling ?? "approval-required")
1208 : "read-only",
1209 } satisfies McpClientSession)
1210 : Effect.fail(
1211 new ServerAuthInvalidCredentialError({
1212 diagnostic: "Only MCP client sessions are accepted here.",
1213 }),
1214 ),
1215 ),
1216 Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
1217 );
1218 };
1219​
1220 const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
1221 sessions
1222 .issue({
1223 subject: MCP_CLIENT_SUBJECT,
1224 method: "bearer-access-token",
1225 scopes: mcpClientScopes(input.access),
1226 ttl: MCP_CLIENT_SESSION_TTL,
1227 ...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
1228 client: { ...input.client, label: input.label, deviceType: "bot" },
1229 })
1230 .pipe(
1231 Effect.map((issued) => ({ token: issued.token, expiresAt: issued.expiresAt })),
1232 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1233 Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
1234 );
1235​
1236 const authenticateBrowserSession: EnvironmentAuth["Service"]["authenticateBrowserSession"] = (
1237 request,
1238 ) => {
1239 const token =
1240 request.cookies[sessions.cookieName] ??
1241 (sessions.legacyCookieName ? request.cookies[sessions.legacyCookieName] : undefined) ??
1242 (devAuth ? request.cookies[devAuth.cookieName] : undefined);
1243 if (!token) return Effect.fail(new ServerAuthMissingCredentialError({}));
1244 return authenticateToken(token).pipe(
1245 Effect.filterOrFail(
1246 (session) => session.method === "browser-session-cookie" && !session.proofKeyThumbprint,
1247 () => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),
1248 ),
1249 Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),
1250 );
1251 };
1252​
1253 const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
1254 code,
1255 access,
1256 ) =>
1257 // No proof key: a code bound to a T3 Connect client's key fails without being spent.
1258 resolveBootstrapGrant(code.trim()).pipe(
1259 Effect.catchTags({
1260 ServerAuthInvalidCredentialError: () =>
1261 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1262 ServerAuthScopeNotGrantedError: () =>
1263 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1264 }),
1265 Effect.flatMap((grant) =>
1266 grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
1267 ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
1268 : mcpClientScopes(access).every((scope) => grant.scopes.includes(scope))
1269 ? Effect.void
1270 : Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1271 ),
1272 Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
1273 );
1274​
1275 return EnvironmentAuth.of({
1276 getDescriptor: () =>
1277 Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
1278 getSessionState,
1279 createBrowserSession,
1280 exchangeBootstrapCredentialForAccessToken,
1281 createPairingLink,
1282 issuePairingCredential,
1283 issueStartupPairingCredential,
1284 listPairingLinks,
1285 revokePairingLink,
1286 issueSession,
1287 listSessions,
1288 revokeSession,
1289 revokeOtherSessionsExcept,
1290 listClientSessions,
1291 revokeClientSession,
1292 revokeOtherClientSessions,
1293 authenticateHttpRequest,
1294 authenticateWebSocketUpgrade,
1295 issueWebSocketTicket,
1296 issueStartupPairingUrl,
1297 authenticateMcpClient,
1298 issueMcpClientSession,
1299 consumeMcpApprovalCode,
1300 authenticateBrowserSession,
1301 });
1302});
1303​
1304export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1305 Layer.provideMerge(PairingGrantStore.layer),
1306 Layer.provideMerge(SessionStore.layer),
1307 Layer.provideMerge(EnvironmentAuthPolicy.layer),
1309​
1310const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig);
1311​
1312export const layerRuntime = layer.pipe(
1313 Layer.provideMerge(layerStorage),
1314 Layer.provideMerge(ServerEnvironment.layerIdentity),