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

EnvironmentAuth.ts

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