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