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

EnvironmentAuth.ts

1,435 lines51.9 KB

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