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

EnvironmentAuth.ts

1,422 lines51.3 KB

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