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

EnvironmentAuth.ts

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