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

EnvironmentAuth.ts

1,406 lines50.8 KB

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