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