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 {
562 readonly sessionId: AuthSessionId;
563 readonly token: string;
564 readonly expiresAt: DateTime.DateTime;
565 },
566 ServerAuthInternalError
567 >;
568 /**
569 * Spends a one-time pairing code as approval for an MCP client with the
570 * given access; the code must hold every scope that access grants.
571 * Proof-bound codes (T3 Connect) are refused without being spent, and
572 * desktop bootstrap grants never qualify.
573 */
574 readonly consumeMcpApprovalCode: (
575 code: string,
576 access: AuthMcpClientAccess,
577 ) => Effect.Effect<void, ServerAuthMcpApprovalCodeError | ServerAuthInternalError>;
578 readonly authenticateBrowserSession: (
579 request: HttpServerRequest.HttpServerRequest,
580 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
581 }
582>()("t3/auth/EnvironmentAuth") {}
583
584type BootstrapExchangeResult = {
585 readonly response: AuthBrowserSessionResult;
586 readonly sessionToken: string;
587 readonly cookieName?: string;
588 readonly expireNormalCookie?: boolean;
589};
590
591const AUTHORIZATION_PREFIX = "Bearer ";
592const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
593const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
594
595const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
596 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
597 const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
598 if (leftCanManage !== rightCanManage) {
599 return leftCanManage ? -1 : 1;
600 }
601 if (left.connected !== right.connected) {
602 return left.connected ? -1 : 1;
603 }
604 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
605};
606
607function toBootstrapExchangeError(
608 cause: PairingGrantStore.BootstrapCredentialError,
609): ServerAuthInvalidCredentialError | ServerAuthInternalError {
610 if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
611 return new ServerAuthBootstrapCredentialValidationError({ cause });
612 }
613
614 return new ServerAuthInvalidCredentialError({
615 cause,
616 });
617}
618
619const rejectMcpClientAudience = <S extends { readonly subject: string }>(session: S) =>
620 session.subject === MCP_CLIENT_SUBJECT
621 ? Effect.fail(
622 new ServerAuthInvalidCredentialError({
623 diagnostic: "MCP client sessions are only accepted by the MCP endpoint.",
624 }),
625 ).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp.")))
626 : Effect.succeed(session);
627
628const mapSessionVerificationErrors = <A, R>(
629 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
630): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
631 effect.pipe(
632 Effect.mapError((cause) =>
633 SessionStore.isSessionCredentialInvalidError(cause)
634 ? new ServerAuthInvalidCredentialError({ cause })
635 : new ServerAuthSessionCredentialValidationError({ cause }),
636 ),
637 );
638
639function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
640 const header = request.headers["authorization"];
641 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
642 return null;
643 }
644 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
645 return token.length > 0 ? token : null;
646}
647
648function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {
649 const header = request.headers["authorization"];
650 if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {
651 return null;
652 }
653 const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();
654 return token.length > 0 ? token : null;
655}
656
657export function selectRequestCredential(
658 request: HttpServerRequest.HttpServerRequest,
659 cookieName: string,
660 legacyCookieName: string | undefined,
661) {
662 const cookieToken = request.cookies[cookieName];
663 if (cookieToken !== undefined) {
664 return { token: cookieToken, source: "cookie" } as const;
665 }
666
667 const bearerToken = parseBearerToken(request);
668 if (bearerToken !== null) {
669 return { token: bearerToken, source: "bearer" } as const;
670 }
671
672 const dpopToken = parseDpopToken(request);
673 if (dpopToken !== null) {
674 return { token: dpopToken, source: "dpop" } as const;
675 }
676
677 const legacyToken = legacyCookieName ? request.cookies[legacyCookieName] : undefined;
678 if (legacyToken !== undefined) {
679 return { token: legacyToken, source: "legacy-cookie" } as const;
680 }
681
682 return undefined;
683}
684
685type RequestCredentialSource = NonNullable<ReturnType<typeof selectRequestCredential>>["source"];
686
687export const isBrowserCookieCredential = (source: RequestCredentialSource | "dev-cookie") =>
688 source === "cookie" || source === "legacy-cookie" || source === "dev-cookie";
689
690function firstHeaderValue(value: string | undefined): string | undefined {
691 const first = value?.split(",")[0]?.trim().toLowerCase();
692 return first && first.length > 0 ? first : undefined;
693}
694
695/**
696 * Browsers send `Origin` on WebSocket upgrades, cross-origin requests, and
697 * non-GET requests, so an absent header means a same-origin read or a
698 * non-browser client. Otherwise the request must be same-origin by the
699 * browser's own `Sec-Fetch-Site` (which survives the dev proxy rewriting
700 * `Host`), come from this server's own host (directly or behind a proxy that
701 * reports `X-Forwarded-Host`), or come from one of the trusted app origins.
702 */
703function isBrowserOriginAllowed(
704 request: HttpServerRequest.HttpServerRequest,
705 trustedOrigins: ReadonlySet<string>,
706): boolean {
707 const origin = request.headers.origin;
708 if (origin === undefined) return true;
709 if (request.headers["sec-fetch-site"] === "same-origin") return true;
710 if (trustedOrigins.has(origin)) return true;
711 let originHost: string;
712 try {
713 originHost = new URL(origin).host.toLowerCase();
714 } catch {
715 return false;
716 }
717 if (originHost === "") return false;
718 return (
719 originHost === firstHeaderValue(request.headers.host) ||
720 originHost === firstHeaderValue(request.headers["x-forwarded-host"])
721 );
722}
723
724/** @public Service construction is part of the canonical Effect module API. */
725export const make = Effect.gen(function* () {
726 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
727 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
728 const sessions = yield* SessionStore.SessionStore;
729 const secretStore = yield* ServerSecretStore.ServerSecretStore;
730 const crypto = yield* Crypto.Crypto;
731 const descriptor = yield* policy.getDescriptor();
732 const config = yield* ServerConfig.ServerConfig;
733 const devAuth = resolveReusableDevAuth(config);
734
735 const authenticateToken = (
736 token: string,
737 ): Effect.Effect<
738 AuthenticatedSession,
739 ServerAuthInvalidCredentialError | ServerAuthInternalError
740 > =>
741 sessions.verify(token).pipe(
742 Effect.tapError((cause) =>
743 SessionStore.isSessionCredentialInvalidError(cause)
744 ? Effect.logWarning("Rejected authenticated session credential.").pipe(
745 Effect.annotateLogs({
746 reason: cause.message,
747 }),
748 )
749 : Effect.void,
750 ),
751 mapSessionVerificationErrors,
752 Effect.flatMap(rejectMcpClientAudience),
753 Effect.map((session) => ({
754 sessionId: session.sessionId,
755 subject: session.subject,
756 method: session.method,
757 scopes: session.scopes,
758 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
759 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
760 })),
761 );
762
763 const resolveRequestCredential = (request: HttpServerRequest.HttpServerRequest) => {
764 const selectedCredential = selectRequestCredential(
765 request,
766 sessions.cookieName,
767 sessions.legacyCookieName,
768 );
769 const hasAuthorization = request.headers.authorization !== undefined;
770 const devCookieToken = devAuth ? request.cookies[devAuth.cookieName] : undefined;
771 return (
772 selectedCredential ??
773 (!hasAuthorization && devCookieToken !== undefined
774 ? { token: devCookieToken, source: "dev-cookie" as const }
775 : undefined)
776 );
777 };
778
779 // Pages the server or its dev setup serves itself. Other origins on the same
780 // site (another localhost port, a LAN IP's other ports) still get the cookie,
781 // so cookie sessions must not authenticate their requests or sockets.
782 const trustedBrowserOrigins = new Set<string>([
783 ...(config.devUrl ? [config.devUrl.origin] : []),
784 ...DESKTOP_RENDERER_ORIGINS,
785 ...config.devAllowedOrigins,
786 ]);
787
788 const authenticateRequest = (
789 request: HttpServerRequest.HttpServerRequest,
790 ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
791 const dpopToken = parseDpopToken(request);
792 const credential = resolveRequestCredential(request);
793 if (!credential?.token) {
794 return Effect.fail(new ServerAuthMissingCredentialError({}));
795 }
796 if (
797 isBrowserCookieCredential(credential.source) &&
798 !isBrowserOriginAllowed(request, trustedBrowserOrigins)
799 ) {
800 return Effect.fail(
801 new ServerAuthInvalidCredentialError({
802 diagnostic: "Browser sessions are only accepted from the app's own origin.",
803 }),
804 );
805 }
806 return authenticateToken(credential.token).pipe(
807 Effect.flatMap((session) => {
808 if (session.proofKeyThumbprint) {
809 if (!dpopToken || dpopToken !== credential.token) {
810 return Effect.fail(
811 new ServerAuthInvalidCredentialError({
812 diagnostic: "DPoP-bound access token requires DPoP authorization.",
813 dpopFailureReason: "invalid_proof",
814 }),
815 );
816 }
817 return verifyRequestDpopProof({
818 request,
819 expectedThumbprint: session.proofKeyThumbprint,
820 expectedAccessToken: dpopToken,
821 }).pipe(
822 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
823 Effect.provideService(Crypto.Crypto, crypto),
824 Effect.as(session),
825 );
826 }
827 if (dpopToken) {
828 return Effect.fail(
829 new ServerAuthInvalidCredentialError({
830 diagnostic: "DPoP authorization requires a proof-bound access token.",
831 dpopFailureReason: "invalid_proof",
832 }),
833 );
834 }
835 return Effect.succeed(session);
836 }),
837 );
838 };
839
840 const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
841 authenticateRequest(request).pipe(
842 Effect.map(
843 (session) =>
844 ({
845 authenticated: true,
846 auth: descriptor,
847 ...authScopeResponse(session.scopes),
848 sessionMethod: session.method,
849 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
850 }) satisfies AuthSessionState,
851 ),
852 Effect.catchIf(isServerAuthCredentialError, () =>
853 Effect.succeed({
854 authenticated: false,
855 auth: descriptor,
856 } satisfies AuthSessionState),
857 ),
858 Effect.withSpan("EnvironmentAuth.getSessionState"),
859 );
860
861 const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn(
862 "EnvironmentAuth.createBrowserSession",
863 )(function* (credential, requestMetadata, previousSessionToken) {
864 if (devAuth?.matches(credential)) {
865 return yield* sessions.verify(credential).pipe(
866 mapSessionVerificationErrors,
867 Effect.flatMap((session) =>
868 DateTime.now.pipe(
869 Effect.map(
870 (now) =>
871 ({
872 response: {
873 authenticated: true,
874 ...authScopeResponse(session.scopes),
875 sessionMethod: session.method,
876 expiresAt: DateTime.toUtc(DateTime.add(now, { days: 30 })),
877 } satisfies AuthBrowserSessionResult,
878 sessionToken: credential,
879 cookieName: devAuth.cookieName,
880 expireNormalCookie: true,
881 }) satisfies BootstrapExchangeResult,
882 ),
883 ),
884 ),
885 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
886 );
887 }
888 const previousSession =
889 previousSessionToken === undefined
890 ? undefined
891 : yield* sessions.verify(previousSessionToken).pipe(
892 Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.void),
893 Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })),
894 );
895 const grant = yield* bootstrapCredentials
896 .consume(credential)
897 .pipe(Effect.mapError(toBootstrapExchangeError));
898 const session = yield* sessions
899 .issue({
900 method: "browser-session-cookie",
901 subject: grant.subject,
902 scopes: grant.scopes,
903 ...(previousSession?.method === "browser-session-cookie"
904 ? { replaceSessionId: previousSession.sessionId }
905 : {}),
906 client: {
907 ...requestMetadata,
908 ...(grant.label ? { label: grant.label } : {}),
909 },
910 })
911 .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })));
912 return {
913 response: {
914 authenticated: true,
915 ...authScopeResponse(session.scopes),
916 sessionMethod: session.method,
917 expiresAt: DateTime.toUtc(session.expiresAt),
918 } satisfies AuthBrowserSessionResult,
919 sessionToken: session.token,
920 } satisfies BootstrapExchangeResult;
921 });
922
923 type ResolvedBootstrapGrant = Pick<
924 PairingGrantStore.BootstrapGrant,
925 "scopes" | "subject" | "label"
926 > & {
927 readonly method: PairingGrantStore.BootstrapGrant["method"] | "reusable-dev-token";
928 };
929 const resolveBootstrapGrant = (
930 credential: string,
931 input?: {
932 readonly proofKeyThumbprint?: string;
933 readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
934 },
935 ): Effect.Effect<
936 ResolvedBootstrapGrant,
937 ServerAuthInvalidCredentialError | ServerAuthInternalError | ServerAuthScopeNotGrantedError
938 > => {
939 if (!devAuth?.matches(credential)) {
940 return bootstrapCredentials
941 .consume(credential, input)
942 .pipe(
943 Effect.mapError((cause) =>
944 cause._tag === "BootstrapCredentialScopeNotGrantedError"
945 ? new ServerAuthScopeNotGrantedError({})
946 : toBootstrapExchangeError(cause),
947 ),
948 );
949 }
950 return sessions.verify(credential).pipe(
951 mapSessionVerificationErrors,
952 Effect.map(
953 (session) =>
954 ({
955 method: "reusable-dev-token",
956 scopes: session.scopes,
957 subject: "reusable-dev-token-child",
958 }) satisfies ResolvedBootstrapGrant,
959 ),
960 );
961 };
962
963 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
964 (credential, requestedScopes, requestMetadata, input) => {
965 return resolveBootstrapGrant(credential, {
966 ...input,
967 ...(requestedScopes !== undefined ? { requestedScopes } : {}),
968 }).pipe(
969 Effect.flatMap((grant) =>
970 Effect.gen(function* () {
971 const grantedScopes =
972 requestedScopes === undefined
973 ? grant.scopes
974 : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope));
975 if (grantedScopes.length === 0) {
976 return yield* new ServerAuthScopeNotGrantedError({});
977 }
978 return yield* sessions
979 .issue({
980 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
981 subject: grant.subject,
982 scopes: grantedScopes,
983 ...(input?.proofKeyThumbprint
984 ? {
985 proofKeyThumbprint: input.proofKeyThumbprint,
986 ttl: Duration.hours(1),
987 }
988 : {}),
989 replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap",
990 client: {
991 ...requestMetadata,
992 ...(grant.label ? { label: grant.label } : {}),
993 },
994 })
995 .pipe(
996 Effect.mapError(
997 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
998 ),
999 );
1000 }),
1001 ),
1002 Effect.flatMap((session) =>
1003 DateTime.now.pipe(
1004 Effect.map(
1005 (now) =>
1006 ({
1007 access_token: session.token,
1008 issued_token_type: AuthAccessTokenType,
1009 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
1010 expires_in: Math.max(
1011 0,
1012 Math.floor(
1013 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
1014 ),
1015 ),
1016 scope: encodeOAuthScope(session.scopes),
1017 }) satisfies AuthAccessTokenResult,
1018 ),
1019 ),
1020 ),
1021 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
1022 );
1023 };
1024
1025 const issuePairingCredentialForSubject = (input: {
1026 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
1027 readonly subject: string;
1028 readonly label?: string;
1029 readonly purpose?: "startup";
1030 }) =>
1031 createPairingLink({
1032 scopes: input.scopes,
1033 subject: input.subject,
1034 ...(input.label ? { label: input.label } : {}),
1035 ...(input.purpose ? { purpose: input.purpose } : {}),
1036 }).pipe(
1037 Effect.map(
1038 (issued) =>
1039 ({
1040 id: issued.id,
1041 credential: issued.credential,
1042 ...(issued.label ? { label: issued.label } : {}),
1043 expiresAt: issued.expiresAt,
1044 }) satisfies AuthPairingCredentialResult,
1045 ),
1046 );
1047
1048 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
1049 "EnvironmentAuth.createPairingLink",
1050 )(
1051 function* (input) {
1052 const createdAt = yield* DateTime.now;
1053 const issued = yield* bootstrapCredentials.issueOneTimeToken({
1054 scopes: input?.scopes ?? AuthStandardClientScopes,
1055 subject: input?.subject ?? "one-time-token",
1056 ...(input?.ttl ? { ttl: input.ttl } : {}),
1057 ...(input?.label ? { label: input.label } : {}),
1058 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
1059 ...(input?.purpose ? { purpose: input.purpose } : {}),
1060 });
1061 return {
1062 id: issued.id,
1063 credential: issued.credential,
1064 scopes: input?.scopes ?? AuthStandardClientScopes,
1065 subject: input?.subject ?? "one-time-token",
1066 ...(issued.label ? { label: issued.label } : {}),
1067 createdAt: DateTime.toUtc(createdAt),
1068 expiresAt: DateTime.toUtc(issued.expiresAt),
1069 } satisfies IssuedPairingLink;
1070 },
1071 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
1072 );
1073
1074 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
1075 bootstrapCredentials.listActive().pipe(
1076 Effect.map((pairingLinks) => {
1077 const excludedSubjects = input?.excludeSubjects ?? [
1078 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1079 ];
1080 return pairingLinks
1081 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
1082 .map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
1083 .toSorted(
1084 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
1085 );
1086 }),
1087 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
1088 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
1089 );
1090
1091 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
1092 bootstrapCredentials.revoke(id).pipe(
1093 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
1094 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
1095 );
1096
1097 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
1098 sessions
1099 .issue({
1100 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1101 method: "bearer-access-token",
1102 scopes: input?.scopes ?? AuthStandardClientScopes,
1103 client: {
1104 ...(input?.label ? { label: input.label } : {}),
1105 deviceType: "bot",
1106 },
1107 ...(input?.ttl ? { ttl: input.ttl } : {}),
1108 })
1109 .pipe(
1110 Effect.map(
1111 (issued) =>
1112 ({
1113 sessionId: issued.sessionId,
1114 token: issued.token,
1115 method: "bearer-access-token",
1116 scopes: issued.scopes,
1117 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1118 client: issued.client,
1119 expiresAt: DateTime.toUtc(issued.expiresAt),
1120 }) satisfies IssuedBearerSession,
1121 ),
1122 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1123 Effect.withSpan("EnvironmentAuth.issueSession"),
1124 );
1125
1126 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
1127 sessions.listActive().pipe(
1128 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
1129 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
1130 Effect.withSpan("EnvironmentAuth.listSessions"),
1131 );
1132
1133 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
1134 sessions.revoke(sessionId).pipe(
1135 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
1136 Effect.withSpan("EnvironmentAuth.revokeSession"),
1137 );
1138
1139 const revokeOtherSessionsExcept: EnvironmentAuth["Service"]["revokeOtherSessionsExcept"] = (
1140 sessionId,
1141 ) =>
1142 sessions.revokeAllExcept(sessionId).pipe(
1143 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
1144 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
1145 );
1146
1147 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
1148 issuePairingCredentialForSubject({
1149 scopes: input?.scopes ?? AuthStandardClientScopes,
1150 subject: "one-time-token",
1151 ...(input?.label ? { label: input.label } : {}),
1152 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
1153
1154 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
1155 () => {
1156 const fallback = issuePairingCredentialForSubject({
1157 scopes: AuthStandardClientScopes,
1158 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1159 purpose: "startup",
1160 });
1161 if (!devAuth) {
1162 return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
1163 }
1164 return sessions.verify(devAuth.credential).pipe(
1165 Effect.map(
1166 (session) =>
1167 ({
1168 id: session.sessionId,
1169 credential: devAuth.credential,
1170 label: "Reusable dev token",
1171 expiresAt: DateTime.toUtc(session.expiresAt ?? REUSABLE_DEV_SESSION_EXPIRES_AT),
1172 }) satisfies AuthPairingCredentialResult,
1173 ),
1174 Effect.catch((cause) =>
1175 SessionStore.isSessionCredentialInvalidError(cause)
1176 ? fallback
1177 : Effect.fail(new ServerAuthPairingLinkCreationError({ cause })),
1178 ),
1179 Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"),
1180 );
1181 };
1182
1183 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
1184 listSessions().pipe(
1185 Effect.map((clientSessions) =>
1186 clientSessions.map((clientSession): AuthClientSession => ({
1187 ...clientSession,
1188 ...authScopeResponse(clientSession.scopes),
1189 current: clientSession.sessionId === currentSessionId,
1190 })),
1191 ),
1192 Effect.withSpan("EnvironmentAuth.listClientSessions"),
1193 );
1194
1195 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
1196 "EnvironmentAuth.revokeClientSession",
1197 )(function* (currentSessionId, targetSessionId) {
1198 if (currentSessionId === targetSessionId) {
1199 return yield* new ServerAuthForbiddenOperationError({});
1200 }
1201 return yield* revokeSession(targetSessionId);
1202 });
1203
1204 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
1205 currentSessionId,
1206 ) =>
1207 revokeOtherSessionsExcept(currentSessionId).pipe(
1208 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
1209 );
1210
1211 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
1212 issueStartupPairingCredential().pipe(
1213 Effect.map((issued) => {
1214 const url = new URL(baseUrl);
1215 url.pathname = "/pair";
1216 url.searchParams.delete("token");
1217 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
1218 return url.toString();
1219 }),
1220 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
1221 );
1222
1223 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
1224 sessions.issueWebSocketToken(session.sessionId).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) {
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 return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
1248 mapSessionVerificationErrors,
1249 Effect.flatMap(rejectMcpClientAudience),
1250 Effect.map((session) => ({
1251 sessionId: session.sessionId,
1252 subject: session.subject,
1253 method: session.method,
1254 scopes: session.scopes,
1255 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1256 })),
1257 );
1258 }
1259 }
1260
1261 return yield* authenticateRequest(request);
1262 });
1263
1264 const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
1265 const token = parseBearerToken(request);
1266 if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
1267 return sessions.verify(token).pipe(
1268 mapSessionVerificationErrors,
1269 Effect.flatMap((session) =>
1270 session.subject === MCP_CLIENT_SUBJECT && session.method === "bearer-access-token"
1271 ? Effect.succeed({
1272 sessionId: session.sessionId,
1273 label: session.client.label ?? "MCP client",
1274 access: session.scopes.includes(AuthOrchestrationOperateScope)
1275 ? (session.runtimeModeCeiling ?? "approval-required")
1276 : "read-only",
1277 } satisfies McpClientSession)
1278 : Effect.fail(
1279 new ServerAuthInvalidCredentialError({
1280 diagnostic: "Only MCP client sessions are accepted here.",
1281 }),
1282 ),
1283 ),
1284 Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
1285 );
1286 };
1287
1288 const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
1289 sessions
1290 .issue({
1291 subject: MCP_CLIENT_SUBJECT,
1292 method: "bearer-access-token",
1293 scopes: mcpClientScopes(input.access),
1294 ttl: MCP_CLIENT_SESSION_TTL,
1295 ...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
1296 client: { ...input.client, label: input.label, deviceType: "bot" },
1297 })
1298 .pipe(
1299 Effect.map((issued) => ({
1300 sessionId: issued.sessionId,
1301 token: issued.token,
1302 expiresAt: issued.expiresAt,
1303 })),
1304 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1305 Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
1306 );
1307
1308 const authenticateBrowserSession: EnvironmentAuth["Service"]["authenticateBrowserSession"] = (
1309 request,
1310 ) => {
1311 const credential = resolveRequestCredential(request);
1312 if (!credential || !isBrowserCookieCredential(credential.source)) {
1313 return Effect.fail(new ServerAuthMissingCredentialError({}));
1314 }
1315 return authenticateRequest(request).pipe(
1316 Effect.filterOrFail(
1317 (session) => session.method === "browser-session-cookie",
1318 () => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),
1319 ),
1320 Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),
1321 );
1322 };
1323
1324 const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
1325 code,
1326 access,
1327 ) =>
1328 resolveBootstrapGrant(code.trim()).pipe(
1329 Effect.catchTags({
1330 ServerAuthInvalidCredentialError: () =>
1331 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1332 ServerAuthScopeNotGrantedError: () =>
1333 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1334 }),
1335 Effect.flatMap((grant) =>
1336 grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
1337 ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
1338 : mcpClientScopes(access).every((scope) => grant.scopes.includes(scope))
1339 ? Effect.void
1340 : Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1341 ),
1342 Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
1343 );
1344
1345 return EnvironmentAuth.of({
1346 getDescriptor: () =>
1347 Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
1348 getSessionState,
1349 createBrowserSession,
1350 exchangeBootstrapCredentialForAccessToken,
1351 createPairingLink,
1352 issuePairingCredential,
1353 issueStartupPairingCredential,
1354 listPairingLinks,
1355 revokePairingLink,
1356 issueSession,
1357 listSessions,
1358 revokeSession,
1359 revokeOtherSessionsExcept,
1360 listClientSessions,
1361 revokeClientSession,
1362 revokeOtherClientSessions,
1363 authenticateHttpRequest,
1364 authenticateWebSocketUpgrade,
1365 issueWebSocketTicket,
1366 issueStartupPairingUrl,
1367 authenticateMcpClient,
1368 issueMcpClientSession,
1369 consumeMcpApprovalCode,
1370 authenticateBrowserSession,
1371 });
1372});
1373
1374export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1375 Layer.provideMerge(PairingGrantStore.layer),
1376 Layer.provideMerge(SessionStore.layer),
1377 Layer.provideMerge(EnvironmentAuthPolicy.layer),
1378);
1379
1380const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig);
1381
1382export const layerRuntime = layer.pipe(
1383 Layer.provideMerge(layerStorage),
1384 Layer.provideMerge(ServerEnvironment.layerIdentity),
1385);