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

EnvironmentAuth.ts

1,400 lines50.6 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 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 });
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;
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;
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;
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;
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 );
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 },
906 ): Effect.Effect<
907 ResolvedBootstrapGrant,
908 ServerAuthInvalidCredentialError | ServerAuthInternalError | ServerAuthScopeNotGrantedError
909 > => {
910 if (!devAuth?.matches(credential)) {
911 return bootstrapCredentials
912 .consume(credential, input)
913 .pipe(
914 Effect.mapError((cause) =>
915 cause._tag === "BootstrapCredentialScopeNotGrantedError"
916 ? new ServerAuthScopeNotGrantedError({})
917 : toBootstrapExchangeError(cause),
918 ),
919 );
920 }
921 return sessions.verify(credential).pipe(
922 mapSessionVerificationErrors,
923 Effect.map(
924 (session) =>
925 ({
926 method: "reusable-dev-token",
927 scopes: session.scopes,
928 subject: "reusable-dev-token-child",
929 }) satisfies ResolvedBootstrapGrant,
930 ),
931 );
932 };
933​
934 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
935 (credential, requestedScopes, requestMetadata, input) => {
936 return resolveBootstrapGrant(credential, {
937 ...input,
938 ...(requestedScopes !== undefined ? { requestedScopes } : {}),
939 }).pipe(
940 Effect.flatMap((grant) =>
941 Effect.gen(function* () {
942 const grantedScopes =
943 requestedScopes === undefined
944 ? grant.scopes
945 : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope));
946 if (grantedScopes.length === 0) {
947 return yield* new ServerAuthScopeNotGrantedError({});
948 }
949 return yield* sessions
950 .issue({
951 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
952 subject: grant.subject,
953 scopes: grantedScopes,
954 ...(input?.proofKeyThumbprint
955 ? {
956 proofKeyThumbprint: input.proofKeyThumbprint,
957 ttl: Duration.hours(1),
958 }
959 : {}),
960 replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap",
961 client: {
962 ...requestMetadata,
963 ...(grant.label ? { label: grant.label } : {}),
964 },
965 })
966 .pipe(
967 Effect.mapError(
968 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
969 ),
970 );
971 }),
972 ),
973 Effect.flatMap((session) =>
974 DateTime.now.pipe(
975 Effect.map(
976 (now) =>
977 ({
978 access_token: session.token,
979 issued_token_type: AuthAccessTokenType,
980 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
981 expires_in: Math.max(
982 0,
983 Math.floor(
984 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
985 ),
986 ),
987 scope: encodeOAuthScope(session.scopes),
988 }) satisfies AuthAccessTokenResult,
989 ),
990 ),
991 ),
992 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
993 );
994 };
995​
996 const issuePairingCredentialForSubject = (input: {
997 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
998 readonly subject: string;
999 readonly label?: string;
1000 readonly purpose?: "startup";
1001 }) =>
1002 createPairingLink({
1003 scopes: input.scopes,
1004 subject: input.subject,
1005 ...(input.label ? { label: input.label } : {}),
1006 ...(input.purpose ? { purpose: input.purpose } : {}),
1007 }).pipe(
1008 Effect.map(
1009 (issued) =>
1010 ({
1011 id: issued.id,
1012 credential: issued.credential,
1013 ...(issued.label ? { label: issued.label } : {}),
1014 expiresAt: issued.expiresAt,
1015 }) satisfies AuthPairingCredentialResult,
1016 ),
1017 );
1018​
1019 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
1020 "EnvironmentAuth.createPairingLink",
1021 )(
1022 function* (input) {
1023 const createdAt = yield* DateTime.now;
1024 const issued = yield* bootstrapCredentials.issueOneTimeToken({
1025 scopes: input?.scopes ?? AuthStandardClientScopes,
1026 subject: input?.subject ?? "one-time-token",
1027 ...(input?.ttl ? { ttl: input.ttl } : {}),
1028 ...(input?.label ? { label: input.label } : {}),
1029 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
1030 ...(input?.purpose ? { purpose: input.purpose } : {}),
1031 });
1032 return {
1033 id: issued.id,
1034 credential: issued.credential,
1035 scopes: input?.scopes ?? AuthStandardClientScopes,
1036 subject: input?.subject ?? "one-time-token",
1037 ...(issued.label ? { label: issued.label } : {}),
1038 createdAt: DateTime.toUtc(createdAt),
1039 expiresAt: DateTime.toUtc(issued.expiresAt),
1040 } satisfies IssuedPairingLink;
1041 },
1042 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
1043 );
1044​
1045 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
1046 bootstrapCredentials.listActive().pipe(
1047 Effect.map((pairingLinks) => {
1048 const excludedSubjects = input?.excludeSubjects ?? [
1049 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1050 ];
1051 return pairingLinks
1052 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
1053 .map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
1054 .toSorted(
1055 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
1056 );
1057 }),
1058 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
1059 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
1060 );
1061​
1062 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
1063 bootstrapCredentials.revoke(id).pipe(
1064 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
1065 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
1066 );
1067​
1068 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
1069 sessions
1070 .issue({
1071 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1072 method: "bearer-access-token",
1073 scopes: input?.scopes ?? AuthStandardClientScopes,
1074 client: {
1075 ...(input?.label ? { label: input.label } : {}),
1076 deviceType: "bot",
1077 },
1078 ...(input?.ttl ? { ttl: input.ttl } : {}),
1079 })
1080 .pipe(
1081 Effect.map(
1082 (issued) =>
1083 ({
1084 sessionId: issued.sessionId,
1085 token: issued.token,
1086 method: "bearer-access-token",
1087 scopes: issued.scopes,
1088 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1089 client: issued.client,
1090 expiresAt: DateTime.toUtc(issued.expiresAt),
1091 }) satisfies IssuedBearerSession,
1092 ),
1093 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1094 Effect.withSpan("EnvironmentAuth.issueSession"),
1095 );
1096​
1097 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
1098 sessions.listActive().pipe(
1099 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
1100 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
1101 Effect.withSpan("EnvironmentAuth.listSessions"),
1102 );
1103​
1104 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
1105 sessions.revoke(sessionId).pipe(
1106 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
1107 Effect.withSpan("EnvironmentAuth.revokeSession"),
1108 );
1109​
1110 const revokeOtherSessionsExcept = (sessionId: AuthSessionId) =>
1111 sessions.revokeAllExcept(sessionId).pipe(
1112 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
1113 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
1114 );
1115​
1116 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
1117 issuePairingCredentialForSubject({
1118 scopes: input?.scopes ?? AuthStandardClientScopes,
1119 subject: "one-time-token",
1120 ...(input?.label ? { label: input.label } : {}),
1121 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
1122​
1123 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
1124 () => {
1125 const fallback = issuePairingCredentialForSubject({
1126 scopes: AuthStandardClientScopes,
1127 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1128 purpose: "startup",
1129 });
1130 if (!devAuth) {
1131 return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
1133 return sessions.verify(devAuth.credential).pipe(
1134 Effect.map(
1135 (session) =>
1136 ({
1137 id: session.sessionId,
1138 credential: devAuth.credential,
1139 label: "Reusable dev token",
1140 expiresAt: DateTime.toUtc(session.expiresAt ?? REUSABLE_DEV_SESSION_EXPIRES_AT),
1141 }) satisfies AuthPairingCredentialResult,
1142 ),
1143 Effect.catch((cause) =>
1144 SessionStore.isSessionCredentialInvalidError(cause)
1145 ? fallback
1146 : Effect.fail(new ServerAuthPairingLinkCreationError({ cause })),
1147 ),
1148 Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"),
1149 );
1150 };
1151​
1152 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
1153 listSessions().pipe(
1154 Effect.map((clientSessions) =>
1155 clientSessions.map((clientSession): AuthClientSession => ({
1156 ...clientSession,
1157 ...authScopeResponse(clientSession.scopes),
1158 current: clientSession.sessionId === currentSessionId,
1159 })),
1160 ),
1161 Effect.withSpan("EnvironmentAuth.listClientSessions"),
1162 );
1163​
1164 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
1165 "EnvironmentAuth.revokeClientSession",
1166 )(function* (currentSessionId, targetSessionId) {
1167 if (currentSessionId === targetSessionId) {
1168 return yield* new ServerAuthForbiddenOperationError({});
1170 return yield* revokeSession(targetSessionId);
1171 });
1172​
1173 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
1174 currentSessionId,
1175 ) =>
1176 revokeOtherSessionsExcept(currentSessionId).pipe(
1177 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
1178 );
1179​
1180 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
1181 issueStartupPairingCredential().pipe(
1182 Effect.map((issued) => {
1183 const url = new URL(baseUrl);
1184 url.pathname = "/pair";
1185 url.searchParams.delete("token");
1186 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
1187 return url.toString();
1188 }),
1189 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
1190 );
1191​
1192 // Only the RPC socket's ticket is bound to the client's proof key. The media
1193 // routes reuse one ticket across <img>, EventSource and several sockets, and
1194 // each of those would need its own single-use proof.
1195 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (
1196 session,
1197 input,
1198 ) =>
1199 sessions
1200 .issueWebSocketToken(session.sessionId, {
1201 ...(input?.use ? { audience: input.use } : {}),
1202 ...(input?.use === "rpc" && session.proofKeyThumbprint
1203 ? { proofKeyThumbprint: session.proofKeyThumbprint }
1204 : {}),
1205 })
1206 .pipe(
1207 Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1208 Effect.map(
1209 (issued) =>
1210 ({
1211 ticket: issued.token,
1212 expiresAt: DateTime.toUtc(issued.expiresAt),
1213 }) satisfies AuthWebSocketTicketResult,
1214 ),
1215 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1216 );
1217​
1218 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
1219 request,
1220 ) =>
1221 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
1222​
1223 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
1224 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request, use) {
1225 const requestUrl = HttpServerRequest.toURL(request);
1226 if (Option.isSome(requestUrl)) {
1227 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
1228 if (websocketTicket && websocketTicket.trim().length > 0) {
1229 const session = yield* sessions
1230 .verifyWebSocketToken(websocketTicket)
1231 .pipe(mapSessionVerificationErrors, Effect.flatMap(rejectMcpClientAudience));
1232 if (session.audience !== undefined && session.audience !== use) {
1233 return yield* new ServerAuthInvalidCredentialError({
1234 diagnostic: `WebSocket ticket was issued for the ${session.audience} route.`,
1235 });
1237 if (session.proofKeyThumbprint) {
1238 // WebSocket clients cannot set headers, so the proof travels in the query.
1239 // The proof hashes the ticket; consuming its jti prevents replay after first use.
1240 // Only encrypted transport prevents an active interceptor from racing that use.
1241 const proof =
1242 request.headers.dpop ??
1243 requestUrl.value.searchParams.get(WEBSOCKET_PROOF_QUERY_PARAM) ??
1244 undefined;
1245 if (!proof) {
1246 return yield* new ServerAuthInvalidCredentialError({
1247 diagnostic: "DPoP-bound WebSocket ticket requires a DPoP proof.",
1248 dpopFailureReason: "invalid_proof",
1249 });
1251 yield* verifyRequestDpopProof({
1252 request,
1253 proof,
1254 expectedThumbprint: session.proofKeyThumbprint,
1255 expectedAccessToken: websocketTicket,
1256 }).pipe(
1257 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
1258 Effect.provideService(Crypto.Crypto, crypto),
1259 );
1261 return {
1262 sessionId: session.sessionId,
1263 subject: session.subject,
1264 method: session.method,
1265 scopes: session.scopes,
1266 ...(session.proofKeyThumbprint
1267 ? { proofKeyThumbprint: session.proofKeyThumbprint }
1268 : {}),
1269 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1270 };
1273​
1274 return yield* authenticateRequest(request);
1275 });
1276​
1277 const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
1278 const token = parseBearerToken(request);
1279 if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
1280 return sessions.verify(token).pipe(
1281 mapSessionVerificationErrors,
1282 Effect.flatMap((session) =>
1283 session.subject === MCP_CLIENT_SUBJECT && session.method === "bearer-access-token"
1284 ? Effect.succeed({
1285 sessionId: session.sessionId,
1286 label: session.client.label ?? "MCP client",
1287 access: session.scopes.includes(AuthOrchestrationOperateScope)
1288 ? (session.runtimeModeCeiling ?? "approval-required")
1289 : "read-only",
1290 peerLink: session.peerLink === true,
1291 } satisfies McpClientSession)
1292 : Effect.fail(
1293 new ServerAuthInvalidCredentialError({
1294 diagnostic: "Only MCP client sessions are accepted here.",
1295 }),
1296 ),
1297 ),
1298 Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
1299 );
1300 };
1301​
1302 const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
1303 sessions
1304 .issue({
1305 subject: MCP_CLIENT_SUBJECT,
1306 method: "bearer-access-token",
1307 scopes: mcpClientScopes(input.access),
1308 ttl: MCP_CLIENT_SESSION_TTL,
1309 ...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
1310 peerLink: input.peerLink,
1311 client: { ...input.client, label: input.label, deviceType: "bot" },
1312 })
1313 .pipe(
1314 Effect.map((issued) => ({
1315 sessionId: issued.sessionId,
1316 token: issued.token,
1317 expiresAt: issued.expiresAt,
1318 })),
1319 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1320 Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
1321 );
1322​
1323 const authenticateBrowserSession: EnvironmentAuth["Service"]["authenticateBrowserSession"] = (
1324 request,
1325 ) => {
1326 const credential = resolveRequestCredential(request);
1327 if (!credential || !isBrowserCookieCredential(credential.source)) {
1328 return Effect.fail(new ServerAuthMissingCredentialError({}));
1330 return authenticateRequest(request).pipe(
1331 Effect.filterOrFail(
1332 (session) => session.method === "browser-session-cookie",
1333 () => new ServerAuthInvalidCredentialError({ diagnostic: "Not a browser session." }),
1334 ),
1335 Effect.withSpan("EnvironmentAuth.authenticateBrowserSession"),
1336 );
1337 };
1338​
1339 const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
1340 code,
1341 access,
1342 ) =>
1343 resolveBootstrapGrant(code.trim()).pipe(
1344 Effect.catchTags({
1345 ServerAuthInvalidCredentialError: () =>
1346 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1347 ServerAuthScopeNotGrantedError: () =>
1348 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1349 }),
1350 Effect.flatMap((grant) =>
1351 grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
1352 ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
1353 : mcpClientScopes(access).every((scope) => grant.scopes.includes(scope))
1354 ? Effect.void
1355 : Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1356 ),
1357 Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
1358 );
1359​
1360 return EnvironmentAuth.of({
1361 getDescriptor: Effect.fn("EnvironmentAuth.getDescriptor")(function () {
1362 return Effect.succeed(descriptor);
1363 }),
1364 getSessionState,
1365 createBrowserSession,
1366 exchangeBootstrapCredentialForAccessToken,
1367 createPairingLink,
1368 issuePairingCredential,
1369 issueStartupPairingCredential,
1370 listPairingLinks,
1371 revokePairingLink,
1372 issueSession,
1373 listSessions,
1374 revokeSession,
1375 listClientSessions,
1376 revokeClientSession,
1377 revokeOtherClientSessions,
1378 authenticateHttpRequest,
1379 authenticateWebSocketUpgrade,
1380 issueWebSocketTicket,
1381 issueStartupPairingUrl,
1382 authenticateMcpClient,
1383 issueMcpClientSession,
1384 consumeMcpApprovalCode,
1385 authenticateBrowserSession,
1386 });
1387});
1388​
1389export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1390 Layer.provideMerge(PairingGrantStore.layer),
1391 Layer.provideMerge(SessionStore.layer),
1392 Layer.provideMerge(EnvironmentAuthPolicy.layer),
1394​
1395const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerConfig);
1396​
1397export const layerRuntime = layer.pipe(
1398 Layer.provideMerge(layerStorage),
1399 Layer.provideMerge(ServerEnvironment.layerIdentity),