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

EnvironmentAuth.ts

1,378 lines49.6 KB

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