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