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