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