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

EnvironmentAuth.ts

1,469 lines53.7 KB

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