The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,799 lines 68.4 KB
Raw
1 import {
2 AuthAccessTokenType,
3 AuthAccessWriteScope,
4 AuthMcpClientAccess,
5 AuthOrchestrationOperateScope,
6 AuthAdministrativeClientScopes,
7 AuthStandardClientScopes,
8 type AuthAccessTokenResult,
9 type AuthBrowserSessionResult,
10 type AuthClientMetadata,
11 type AuthClientSession,
12 type AuthConnectDevice,
13 type AuthCreatePairingCredentialInput,
14 type AuthEnvironmentScope,
15 type AuthPairingLink,
16 type AuthPairingCredentialResult,
17 type AuthSessionId,
18 type AuthSessionState,
19 authScopeResponse,
20 type ServerAuthDescriptor,
21 type ServerAuthSessionMethod,
22 type AuthWebSocketTicketResult,
23 type AuthWebSocketTicketUse,
24 DpopFailureReason,
25 type DpopFailureReason as DpopFailureReasonType,
26 mcpClientScopes,
27 } from "@t3tools/contracts";
28 import { isLocalLoopbackHost } from "@t3tools/shared/hostClassification";
29 import { encodeOAuthScope } from "@t3tools/shared/oauthScope";
30 import * as Context from "effect/Context";
31 import * as Digest from "effect/crypto/Digest";
32 import * as DateTime from "effect/DateTime";
33 import * as Duration from "effect/Duration";
34 import * as Effect from "effect/Effect";
35 import * as Layer from "effect/Layer";
36 import * as Option from "effect/Option";
37 import * as Redacted from "effect/Redacted";
38 import * as Schema from "effect/Schema";
39 import * as Semaphore from "effect/Semaphore";
40 import * as HttpServerRequest from "effect/http/HttpServerRequest";
41
42 import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
43 import * as ServerConfig from "../config.ts";
44 import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
45 import * as PairingGrantStore from "./PairingGrantStore.ts";
46 import * as ServerSecretStore from "./ServerSecretStore.ts";
47 import * as SessionStore from "./SessionStore.ts";
48 import { REUSABLE_DEV_SESSION_EXPIRES_AT, resolveReusableDevAuth } from "./ReusableDevAuth.ts";
49 import { verifyRequestDpopProof } from "./dpop.ts";
50 import { DESKTOP_RENDERER_ORIGINS } from "../httpCors.ts";
51 import * as SqlitePersistence from "../persistence/Sqlite.ts";
52 import * as ManagedLimits from "../policy/managedLimits.ts";
53 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
54 import {
55 MCP_APPROVAL_SUBJECT_PREFIX,
56 PEER_LINK_PAIRING_SUBJECT_PREFIX,
57 } from "../persistence/AuthPairingLinks.ts";
58 import { requestUrl } from "../requestUrl.ts";
59
60 const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
61 export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
62 /** Sessions and pairing links T3 Connect minted for a device signed in to the linked account. */
63 export const CLOUD_CONNECT_SUBJECT = "cloud-connect";
64
65 export interface IssuedPairingLink {
66 readonly id: string;
67 readonly credential: string;
68 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
69 readonly subject: string;
70 readonly label?: string;
71 readonly createdAt: DateTime.Utc;
72 readonly expiresAt: DateTime.Utc;
73 }
74
75 export interface IssuedBearerSession {
76 readonly sessionId: AuthSessionId;
77 readonly token: string;
78 readonly method: "bearer-access-token";
79 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
80 readonly subject: string;
81 readonly client: AuthClientMetadata;
82 readonly expiresAt: DateTime.Utc;
83 }
84
85 // MCP client tokens are restricted to /mcp; HTTP API and WebSocket RPC would bypass their access cap.
86 const MCP_CLIENT_SUBJECT = "mcp-client";
87 const MCP_CLIENT_SESSION_TTL = Duration.days(30);
88 // A peer link's session moves back out to its full lifetime when a call finds it this far
89 // short, so a used link never expires and a busy one writes at most once per step.
90 const PEER_LINK_RENEWAL_STEP = Duration.days(1);
91
92 // A device pairing with its DPoP key renews the session itself, so the token can be short and
93 // the device stays signed in while used. One idle for the whole window pairs again.
94 const RENEWABLE_ACCESS_TOKEN_TTL = Duration.hours(1);
95 const RENEWABLE_SESSION_WINDOW = Duration.days(30);
96 const PAIRING_LINK_SUBJECT = "one-time-token";
97
98 export interface McpClientSession {
99 readonly sessionId: AuthSessionId;
100 readonly label: string;
101 readonly access: AuthMcpClientAccess;
102 /** Another T3 Code environment's link, whose work here stays within it. */
103 readonly peerLink: boolean;
104 /** When a peer link's session ends unless it is used again; the linking side keeps this. */
105 readonly linkExpiresAt?: DateTime.Utc;
106 }
107
108 export interface AuthenticatedSession {
109 readonly sessionId: AuthSessionId;
110 readonly subject: string;
111 readonly method: ServerAuthSessionMethod;
112 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
113 readonly proofKeyThumbprint?: string;
114 readonly expiresAt?: DateTime.DateTime;
115 }
116
117 const serverAuthInternalErrorContext = {
118 cause: Schema.Defect(),
119 };
120
121 export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedError<ServerAuthBootstrapCredentialValidationError>()(
122 "ServerAuthBootstrapCredentialValidationError",
123 {
124 ...serverAuthInternalErrorContext,
125 },
126 ) {
127 override get message(): string {
128 return "Failed to validate bootstrap credential.";
129 }
130 }
131
132 export class ServerAuthSessionCredentialValidationError extends Schema.TaggedError<ServerAuthSessionCredentialValidationError>()(
133 "ServerAuthSessionCredentialValidationError",
134 {
135 ...serverAuthInternalErrorContext,
136 },
137 ) {
138 override get message(): string {
139 return "Failed to validate session credential.";
140 }
141 }
142
143 export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedError<ServerAuthAuthenticatedSessionIssueError>()(
144 "ServerAuthAuthenticatedSessionIssueError",
145 {
146 ...serverAuthInternalErrorContext,
147 },
148 ) {
149 override get message(): string {
150 return "Failed to issue authenticated session.";
151 }
152 }
153
154 export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedError<ServerAuthAuthenticatedAccessTokenIssueError>()(
155 "ServerAuthAuthenticatedAccessTokenIssueError",
156 {
157 ...serverAuthInternalErrorContext,
158 },
159 ) {
160 override get message(): string {
161 return "Failed to issue authenticated access token.";
162 }
163 }
164
165 export class ServerAuthPairingLinkCreationError extends Schema.TaggedError<ServerAuthPairingLinkCreationError>()(
166 "ServerAuthPairingLinkCreationError",
167 {
168 ...serverAuthInternalErrorContext,
169 },
170 ) {
171 override get message(): string {
172 return "Failed to create pairing link.";
173 }
174 }
175
176 export class ServerAuthPairingLinksListError extends Schema.TaggedError<ServerAuthPairingLinksListError>()(
177 "ServerAuthPairingLinksListError",
178 {
179 ...serverAuthInternalErrorContext,
180 },
181 ) {
182 override get message(): string {
183 return "Failed to list pairing links.";
184 }
185 }
186
187 export class ServerAuthPairingLinkRevocationError extends Schema.TaggedError<ServerAuthPairingLinkRevocationError>()(
188 "ServerAuthPairingLinkRevocationError",
189 {
190 ...serverAuthInternalErrorContext,
191 },
192 ) {
193 override get message(): string {
194 return "Failed to revoke pairing link.";
195 }
196 }
197
198 export class ServerAuthSessionTokenIssueError extends Schema.TaggedError<ServerAuthSessionTokenIssueError>()(
199 "ServerAuthSessionTokenIssueError",
200 {
201 ...serverAuthInternalErrorContext,
202 },
203 ) {
204 override get message(): string {
205 return "Failed to issue session token.";
206 }
207 }
208
209 export class ServerAuthSessionsListError extends Schema.TaggedError<ServerAuthSessionsListError>()(
210 "ServerAuthSessionsListError",
211 {
212 ...serverAuthInternalErrorContext,
213 },
214 ) {
215 override get message(): string {
216 return "Failed to list sessions.";
217 }
218 }
219
220 export class ServerAuthSessionRevocationError extends Schema.TaggedError<ServerAuthSessionRevocationError>()(
221 "ServerAuthSessionRevocationError",
222 {
223 ...serverAuthInternalErrorContext,
224 },
225 ) {
226 override get message(): string {
227 return "Failed to revoke session.";
228 }
229 }
230
231 export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedError<ServerAuthOtherSessionsRevocationError>()(
232 "ServerAuthOtherSessionsRevocationError",
233 {
234 ...serverAuthInternalErrorContext,
235 },
236 ) {
237 override get message(): string {
238 return "Failed to revoke other sessions.";
239 }
240 }
241
242 export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedError<ServerAuthWebSocketTokenIssueError>()(
243 "ServerAuthWebSocketTokenIssueError",
244 {
245 ...serverAuthInternalErrorContext,
246 },
247 ) {
248 override get message(): string {
249 return "Failed to issue websocket token.";
250 }
251 }
252
253 export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedError<ServerAuthDpopReplayStateRecordError>()(
254 "ServerAuthDpopReplayStateRecordError",
255 {
256 ...serverAuthInternalErrorContext,
257 },
258 ) {
259 override get message(): string {
260 return "Failed to record DPoP proof replay state.";
261 }
262 }
263
264 export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedError<ServerAuthDpopReplayKeyCalculationError>()(
265 "ServerAuthDpopReplayKeyCalculationError",
266 {
267 ...serverAuthInternalErrorContext,
268 },
269 ) {
270 override get message(): string {
271 return "Failed to calculate DPoP replay key.";
272 }
273 }
274
275 export class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedError<ServerAuthLinkedCloudAccountVerificationError>()(
276 "ServerAuthLinkedCloudAccountVerificationError",
277 {
278 ...serverAuthInternalErrorContext,
279 },
280 ) {
281 override get message(): string {
282 return "Could not verify the linked cloud account.";
283 }
284 }
285
286 export class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedError<ServerAuthLinkedCloudAccountReadError>()(
287 "ServerAuthLinkedCloudAccountReadError",
288 {
289 ...serverAuthInternalErrorContext,
290 },
291 ) {
292 override get message(): string {
293 return "Could not read the linked cloud account.";
294 }
295 }
296
297 export class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedError<ServerAuthLinkedCloudAccountMissingError>()(
298 "ServerAuthLinkedCloudAccountMissingError",
299 {},
300 ) {
301 override get message(): string {
302 return "Cloud linked user is not installed for this environment.";
303 }
304 }
305
306 export class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedError<ServerAuthCloudLinkJwtSigningError>()(
307 "ServerAuthCloudLinkJwtSigningError",
308 {
309 ...serverAuthInternalErrorContext,
310 },
311 ) {
312 override get message(): string {
313 return "Failed to sign cloud link JWT.";
314 }
315 }
316
317 export class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedError<ServerAuthCloudMintPublicKeyMissingError>()(
318 "ServerAuthCloudMintPublicKeyMissingError",
319 {},
320 ) {
321 override get message(): string {
322 return "Cloud mint public key is not installed for this environment.";
323 }
324 }
325
326 export class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedError<ServerAuthCloudRelayIssuerMissingError>()(
327 "ServerAuthCloudRelayIssuerMissingError",
328 {},
329 ) {
330 override get message(): string {
331 return "Cloud relay issuer is not installed for this environment.";
332 }
333 }
334
335 export class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedError<ServerAuthCloudHealthJwtSigningError>()(
336 "ServerAuthCloudHealthJwtSigningError",
337 {
338 ...serverAuthInternalErrorContext,
339 },
340 ) {
341 override get message(): string {
342 return "Failed to sign cloud health JWT.";
343 }
344 }
345
346 export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedError<ServerAuthCloudMintJwtSigningError>()(
347 "ServerAuthCloudMintJwtSigningError",
348 {
349 ...serverAuthInternalErrorContext,
350 },
351 ) {
352 override get message(): string {
353 return "Failed to sign cloud mint JWT.";
354 }
355 }
356
357 export class ServerAuthConnectDevicesError extends Schema.TaggedError<ServerAuthConnectDevicesError>()(
358 "ServerAuthConnectDevicesError",
359 {
360 ...serverAuthInternalErrorContext,
361 },
362 ) {
363 override get message(): string {
364 return "Failed to update T3 Connect devices.";
365 }
366 }
367
368 export const ServerAuthInternalError = Schema.Union([
369 ServerAuthBootstrapCredentialValidationError,
370 ServerAuthSessionCredentialValidationError,
371 ServerAuthAuthenticatedSessionIssueError,
372 ServerAuthAuthenticatedAccessTokenIssueError,
373 ServerAuthPairingLinkCreationError,
374 ServerAuthPairingLinksListError,
375 ServerAuthPairingLinkRevocationError,
376 ServerAuthSessionTokenIssueError,
377 ServerAuthSessionsListError,
378 ServerAuthSessionRevocationError,
379 ServerAuthOtherSessionsRevocationError,
380 ServerAuthWebSocketTokenIssueError,
381 ServerAuthDpopReplayStateRecordError,
382 ServerAuthDpopReplayKeyCalculationError,
383 ServerAuthLinkedCloudAccountVerificationError,
384 ServerAuthLinkedCloudAccountReadError,
385 ServerAuthLinkedCloudAccountMissingError,
386 ServerAuthCloudLinkJwtSigningError,
387 ServerAuthCloudMintPublicKeyMissingError,
388 ServerAuthCloudRelayIssuerMissingError,
389 ServerAuthCloudHealthJwtSigningError,
390 ServerAuthCloudMintJwtSigningError,
391 ServerAuthConnectDevicesError,
392 ]);
393 export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
394 export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
395
396 export class ServerAuthMissingCredentialError extends Schema.TaggedError<ServerAuthMissingCredentialError>()(
397 "ServerAuthMissingCredentialError",
398 {},
399 ) {
400 override get message(): string {
401 return "Server authentication credential is missing.";
402 }
403 }
404
405 export class ServerAuthInvalidCredentialError extends Schema.TaggedError<ServerAuthInvalidCredentialError>()(
406 "ServerAuthInvalidCredentialError",
407 {
408 diagnostic: Schema.optional(Schema.String),
409 dpopFailureReason: Schema.optionalKey(DpopFailureReason),
410 cause: Schema.optional(Schema.Defect()),
411 },
412 ) {
413 override get message(): string {
414 return "Server authentication credential is invalid.";
415 }
416 }
417
418 export const ServerAuthCredentialError = Schema.Union([
419 ServerAuthMissingCredentialError,
420 ServerAuthInvalidCredentialError,
421 ]);
422 export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
423 export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
424 export const serverAuthCredentialReason = (
425 error: ServerAuthCredentialError,
426 ): "missing_credential" | "invalid_credential" =>
427 error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
428
429 export const serverAuthDpopFailureReason = (
430 error: ServerAuthCredentialError,
431 ): DpopFailureReasonType | undefined =>
432 error._tag === "ServerAuthInvalidCredentialError" ? error.dpopFailureReason : undefined;
433
434 export class ServerAuthInvalidScopeError extends Schema.TaggedError<ServerAuthInvalidScopeError>()(
435 "ServerAuthInvalidScopeError",
436 {},
437 ) {
438 override get message(): string {
439 return "The requested authentication scope is invalid.";
440 }
441 }
442
443 export class ServerAuthScopeNotGrantedError extends Schema.TaggedError<ServerAuthScopeNotGrantedError>()(
444 "ServerAuthScopeNotGrantedError",
445 {},
446 ) {
447 override get message(): string {
448 return "The requested authentication scope was not granted.";
449 }
450 }
451
452 export const ServerAuthInvalidRequestError = Schema.Union([
453 ServerAuthInvalidScopeError,
454 ServerAuthScopeNotGrantedError,
455 ]);
456 export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
457 export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
458 export const serverAuthInvalidRequestReason = (
459 error: ServerAuthInvalidRequestError,
460 ): "invalid_scope" | "scope_not_granted" =>
461 error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
462
463 /** The credential is fine, but the host has not approved this T3 Connect device yet. */
464 export class ServerAuthConnectApprovalPendingError extends Schema.TaggedError<ServerAuthConnectApprovalPendingError>()(
465 "ServerAuthConnectApprovalPendingError",
466 {},
467 ) {
468 override get message(): string {
469 return "This T3 Connect device is waiting for approval.";
470 }
471 }
472
473 export class ServerAuthMcpApprovalCodeError extends Schema.TaggedError<ServerAuthMcpApprovalCodeError>()(
474 "ServerAuthMcpApprovalCodeError",
475 { reason: Schema.Literals(["unknown_or_used", "not_a_pairing_code", "insufficient_scope"]) },
476 ) {
477 override get message(): string {
478 return this.reason === "insufficient_scope"
479 ? "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."
480 : this.reason === "not_a_pairing_code"
481 ? "That is not a one-time pairing code."
482 : "That pairing code is unknown, expired, or already used.";
483 }
484 }
485
486 export class ServerAuthForbiddenOperationError extends Schema.TaggedError<ServerAuthForbiddenOperationError>()(
487 "ServerAuthForbiddenOperationError",
488 {},
489 ) {
490 override get message(): string {
491 return "The current authentication session cannot revoke itself.";
492 }
493 }
494
495 export class EnvironmentAuth extends Context.Service<
496 EnvironmentAuth,
497 {
498 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
499 readonly getSessionState: (
500 request: HttpServerRequest.HttpServerRequest,
501 ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
502 readonly createBrowserSession: (
503 credential: string,
504 requestMetadata: AuthClientMetadata,
505 previousSessionToken?: string,
506 ) => Effect.Effect<
507 {
508 readonly response: AuthBrowserSessionResult;
509 readonly sessionToken: string;
510 readonly cookieName?: string;
511 readonly expireNormalCookie?: boolean;
512 },
513 ServerAuthInvalidCredentialError | ServerAuthInternalError
514 >;
515 readonly exchangeBootstrapCredentialForAccessToken: (
516 credential: string,
517 requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
518 requestMetadata: AuthClientMetadata,
519 input?: {
520 readonly proofKeyThumbprint?: string;
521 },
522 ) => Effect.Effect<
523 AuthAccessTokenResult,
524 | ServerAuthInvalidCredentialError
525 | ServerAuthInvalidRequestError
526 | ServerAuthConnectApprovalPendingError
527 | ServerAuthInternalError
528 >;
529 readonly renewAccessToken: (
530 accessToken: string,
531 proofKeyThumbprint: string,
532 consumeProof: Effect.Effect<void, ServerAuthInvalidCredentialError | ServerAuthInternalError>,
533 ) => Effect.Effect<
534 AuthAccessTokenResult,
535 ServerAuthInvalidCredentialError | ServerAuthInternalError
536 >;
537 readonly createPairingLink: (input?: {
538 readonly ttl?: Duration.Duration;
539 readonly label?: string;
540 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
541 readonly subject?: string;
542 readonly proofKeyThumbprint?: string;
543 readonly purpose?: "startup";
544 readonly mcpApproval?: AuthMcpClientAccess;
545 readonly requiresConnectApproval?: boolean;
546 }) => Effect.Effect<
547 IssuedPairingLink,
548 ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
549 >;
550 /**
551 * The one-time credential T3 Connect hands a device. With approval required, an untrusted
552 * device key gets one that waits for approval, and keeps it across retries.
553 */
554 readonly issueConnectCredential: (input: {
555 readonly proofKeyThumbprint: string;
556 readonly requireApproval: boolean;
557 }) => Effect.Effect<
558 { readonly credential: string; readonly expiresAt: DateTime.Utc },
559 ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
560 >;
561 readonly approveConnectDevice: (
562 pairingLinkId: string,
563 ) => Effect.Effect<boolean, ServerAuthInternalError>;
564 /** Pairing link ids of waiting devices that show this code; more than one is ambiguous. */
565 readonly connectRequestsShowingCode: (
566 verificationCode: string,
567 ) => Effect.Effect<ReadonlyArray<string>, ServerAuthInternalError>;
568 /** Trusted devices that show this code; more than one is ambiguous. */
569 readonly connectDevicesShowingCode: (
570 verificationCode: string,
571 ) => Effect.Effect<ReadonlyArray<AuthConnectDevice>, ServerAuthInternalError>;
572 readonly listConnectDevices: () => Effect.Effect<
573 ReadonlyArray<AuthConnectDevice>,
574 ServerAuthInternalError
575 >;
576 /** Stops trusting a device key and ends the sessions it holds. */
577 readonly revokeConnectDevice: (
578 proofKeyThumbprint: string,
579 ) => Effect.Effect<boolean, ServerAuthInternalError>;
580 readonly issuePairingCredential: (
581 input?: AuthCreatePairingCredentialInput,
582 ) => Effect.Effect<
583 AuthPairingCredentialResult,
584 ServerAuthInternalError | ManagedLimits.ManagedPolicyRefusedError
585 >;
586 readonly issueStartupPairingCredential: () => Effect.Effect<
587 AuthPairingCredentialResult,
588 ServerAuthInternalError
589 >;
590 readonly listPairingLinks: (input?: {
591 readonly excludeSubjects?: ReadonlyArray<string>;
592 }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
593 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
594 readonly issueSession: (input?: {
595 readonly ttl?: Duration.Duration;
596 readonly subject?: string;
597 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
598 readonly label?: string;
599 }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
600 readonly listSessions: () => Effect.Effect<
601 ReadonlyArray<AuthClientSession>,
602 ServerAuthInternalError
603 >;
604 readonly revokeSession: (
605 sessionId: AuthSessionId,
606 ) => Effect.Effect<boolean, ServerAuthInternalError>;
607 readonly listClientSessions: (
608 currentSessionId: AuthSessionId,
609 ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
610 /** Revokes a session; one bound to a device key takes the device's trust and sessions with it. */
611 readonly revokeClient: (
612 sessionId: AuthSessionId,
613 ) => Effect.Effect<boolean, ServerAuthInternalError>;
614 readonly revokeClientSession: (
615 currentSessionId: AuthSessionId,
616 targetSessionId: AuthSessionId,
617 ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
618 readonly revokeOtherClientSessions: (
619 currentSessionId: AuthSessionId,
620 ) => Effect.Effect<number, ServerAuthInternalError>;
621 readonly authenticateHttpRequest: (
622 request: HttpServerRequest.HttpServerRequest,
623 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
624 readonly authenticateWebSocketUpgrade: (
625 request: HttpServerRequest.HttpServerRequest,
626 use: AuthWebSocketTicketUse,
627 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
628 readonly issueWebSocketTicket: (
629 session: Pick<AuthenticatedSession, "sessionId" | "proofKeyThumbprint">,
630 input?: { readonly use?: AuthWebSocketTicketUse },
631 ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
632 readonly issueStartupPairingUrl: (
633 baseUrl: string,
634 ) => Effect.Effect<string, ServerAuthInternalError>;
635 readonly authenticateMcpClient: (
636 request: HttpServerRequest.HttpServerRequest,
637 ) => Effect.Effect<McpClientSession, ServerAuthCredentialError | ServerAuthInternalError>;
638 readonly issueMcpClientSession: (input: {
639 readonly label: string;
640 readonly access: AuthMcpClientAccess;
641 readonly peerLink: boolean;
642 readonly client: AuthClientMetadata;
643 }) => Effect.Effect<
644 {
645 readonly sessionId: AuthSessionId;
646 readonly token: string;
647 readonly expiresAt: DateTime.DateTime;
648 },
649 ServerAuthInternalError
650 >;
651 /**
652 * Spends a code covering all granted scopes and returns the level it approves. A level-bound
653 * code must name `access`. Rejects desktop grants and leaves refused codes unspent.
654 */
655 readonly consumeMcpApprovalCode: (
656 code: string,
657 access: AuthMcpClientAccess,
658 peerLink?: boolean,
659 ) => Effect.Effect<
660 AuthMcpClientAccess,
661 ServerAuthMcpApprovalCodeError | ServerAuthInternalError
662 >;
663 }
664 >()("t3/auth/EnvironmentAuth") {}
665
666 type BootstrapExchangeResult = {
667 readonly response: AuthBrowserSessionResult;
668 readonly sessionToken: string;
669 readonly cookieName?: string;
670 readonly expireNormalCookie?: boolean;
671 };
672
673 const AUTHORIZATION_PREFIX = "Bearer ";
674 const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
675 const WebSocketUpgradeQuery = Schema.Struct({
676 wsTicket: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
677 dpop: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)),
678 });
679 const decodeWebSocketUpgradeQuery = Schema.decodeEffect(WebSocketUpgradeQuery);
680
681 const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
682 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
683 const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
684 if (leftCanManage !== rightCanManage) {
685 return leftCanManage ? -1 : 1;
686 }
687 if (left.connected !== right.connected) {
688 return left.connected ? -1 : 1;
689 }
690 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
691 };
692
693 function toBootstrapExchangeError(
694 cause: PairingGrantStore.BootstrapCredentialError,
695 ): ServerAuthInvalidCredentialError | ServerAuthInternalError {
696 if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
697 return new ServerAuthBootstrapCredentialValidationError({ cause });
698 }
699
700 return new ServerAuthInvalidCredentialError({
701 cause,
702 });
703 }
704
705 const rejectMcpClientAudience = <S extends { readonly subject: string }>(session: S) =>
706 session.subject === MCP_CLIENT_SUBJECT
707 ? Effect.fail(
708 new ServerAuthInvalidCredentialError({
709 diagnostic: "MCP client sessions are only accepted by the MCP endpoint.",
710 }),
711 ).pipe(Effect.tap(() => Effect.logWarning("Rejected an MCP client session outside /mcp.")))
712 : Effect.succeed(session);
713
714 const toSessionVerificationError = (cause: SessionStore.SessionCredentialError) =>
715 SessionStore.isSessionCredentialInvalidError(cause)
716 ? new ServerAuthInvalidCredentialError({ cause })
717 : new ServerAuthSessionCredentialValidationError({ cause });
718
719 const mapSessionVerificationErrors = <A, R>(
720 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
721 ): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
722 effect.pipe(Effect.mapError(toSessionVerificationError));
723
724 export function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
725 const header = request.headers["authorization"];
726 if (typeof header !== "string" || !/^Bearer /i.test(header)) {
727 return null;
728 }
729 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
730 return token.length > 0 ? token : null;
731 }
732
733 function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {
734 const header = request.headers["authorization"];
735 if (typeof header !== "string" || !/^DPoP /i.test(header)) {
736 return null;
737 }
738 const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();
739 return token.length > 0 ? token : null;
740 }
741
742 export function selectRequestCredential(
743 request: HttpServerRequest.HttpServerRequest,
744 cookieName: string,
745 legacyCookieName: string | undefined,
746 ) {
747 const cookieToken = request.cookies[cookieName];
748 if (cookieToken) {
749 return { token: cookieToken, source: "cookie" } as const;
750 }
751
752 const bearerToken = parseBearerToken(request);
753 if (bearerToken !== null) {
754 return { token: bearerToken, source: "bearer" } as const;
755 }
756
757 const dpopToken = parseDpopToken(request);
758 if (dpopToken !== null) {
759 return { token: dpopToken, source: "dpop" } as const;
760 }
761
762 const legacyToken = legacyCookieName ? request.cookies[legacyCookieName] : undefined;
763 if (legacyToken !== undefined) {
764 return { token: legacyToken, source: "legacy-cookie" } as const;
765 }
766
767 return undefined;
768 }
769
770 type RequestCredentialSource = NonNullable<ReturnType<typeof selectRequestCredential>>["source"];
771
772 export const isBrowserCookieCredential = (source: RequestCredentialSource | "dev-cookie") =>
773 source === "cookie" || source === "legacy-cookie" || source === "dev-cookie";
774
775 function firstHeaderValue(value: string | undefined): string | undefined {
776 const first = value?.split(",")[0]?.trim().toLowerCase();
777 return first && first.length > 0 ? first : undefined;
778 }
779
780 // Missing Origin allows same-origin reads and non-browser clients; otherwise require
781 // same-origin Sec-Fetch-Site, this server's host (including X-Forwarded-Host), or a trusted app origin.
782 function isBrowserOriginAllowed(
783 request: HttpServerRequest.HttpServerRequest,
784 trustedOrigins: ReadonlySet<string>,
785 ): boolean {
786 const origin = request.headers.origin;
787 if (origin === undefined) return true;
788 if (request.headers["sec-fetch-site"] === "same-origin") return true;
789 if (trustedOrigins.has(origin)) return true;
790 let originHost: string;
791 try {
792 originHost = new URL(origin).host.toLowerCase();
793 } catch {
794 return false;
795 }
796 if (originHost === "") return false;
797 return (
798 originHost === firstHeaderValue(request.headers.host) ||
799 originHost === firstHeaderValue(request.headers["x-forwarded-host"])
800 );
801 }
802
803 /** @public */
804 export const make = Effect.gen(function* () {
805 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
806 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
807 const sessions = yield* SessionStore.SessionStore;
808 const secretStore = yield* ServerSecretStore.ServerSecretStore;
809 const digest = yield* Digest.Digest;
810 const descriptor = yield* policy.getDescriptor();
811 const config = yield* ServerConfig.ServerConfig;
812 const managedPolicy = yield* ManagedPolicy.ManagedPolicy;
813 const devAuth = resolveReusableDevAuth(config);
814
815 const authenticateToken = (
816 token: string,
817 ): Effect.Effect<
818 AuthenticatedSession,
819 ServerAuthInvalidCredentialError | ServerAuthInternalError
820 > =>
821 sessions.verify(token).pipe(
822 Effect.tapError((cause) =>
823 SessionStore.isSessionCredentialInvalidError(cause)
824 ? Effect.logWarning("Rejected authenticated session credential.").pipe(
825 Effect.annotateLogs({
826 reason: cause.message,
827 }),
828 )
829 : Effect.void,
830 ),
831 mapSessionVerificationErrors,
832 Effect.flatMap(rejectMcpClientAudience),
833 Effect.map((session) => ({
834 sessionId: session.sessionId,
835 subject: session.subject,
836 method: session.method,
837 scopes: session.scopes,
838 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
839 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
840 })),
841 );
842
843 const resolveRequestCredential = (request: HttpServerRequest.HttpServerRequest) => {
844 const selectedCredential = selectRequestCredential(
845 request,
846 sessions.cookieName,
847 sessions.legacyCookieName,
848 );
849 const hasAuthorization = request.headers.authorization !== undefined;
850 const devCookieToken = devAuth ? request.cookies[devAuth.cookieName] : undefined;
851 return (
852 selectedCredential ??
853 (!hasAuthorization && devCookieToken !== undefined
854 ? { token: devCookieToken, source: "dev-cookie" as const }
855 : undefined)
856 );
857 };
858
859 // Cookies span ports; reject cookie-authenticated requests and sockets from other same-site origins.
860 const trustedBrowserOrigins = new Set<string>([
861 ...(config.devUrl ? [config.devUrl.origin] : []),
862 ...DESKTOP_RENDERER_ORIGINS,
863 ...config.devAllowedOrigins,
864 ]);
865
866 const authenticateRequest = (
867 request: HttpServerRequest.HttpServerRequest,
868 ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
869 const dpopToken = parseDpopToken(request);
870 const credential = resolveRequestCredential(request);
871 if (!credential?.token) {
872 return Effect.fail(new ServerAuthMissingCredentialError({}));
873 }
874 if (
875 isBrowserCookieCredential(credential.source) &&
876 !isBrowserOriginAllowed(request, trustedBrowserOrigins)
877 ) {
878 return Effect.fail(
879 new ServerAuthInvalidCredentialError({
880 diagnostic: "Browser sessions are only accepted from the app's own origin.",
881 }),
882 );
883 }
884 return authenticateToken(credential.token).pipe(
885 Effect.flatMap((session) => {
886 if (session.proofKeyThumbprint) {
887 if (!dpopToken || dpopToken !== credential.token) {
888 return Effect.fail(
889 new ServerAuthInvalidCredentialError({
890 diagnostic: "DPoP-bound access token requires DPoP authorization.",
891 dpopFailureReason: "invalid_proof",
892 }),
893 );
894 }
895 return verifyRequestDpopProof({
896 request,
897 expectedThumbprint: session.proofKeyThumbprint,
898 expectedAccessToken: dpopToken,
899 }).pipe(
900 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
901 Effect.provideService(Digest.Digest, digest),
902 Effect.as(session),
903 );
904 }
905 if (dpopToken) {
906 return Effect.fail(
907 new ServerAuthInvalidCredentialError({
908 diagnostic: "DPoP authorization requires a proof-bound access token.",
909 dpopFailureReason: "invalid_proof",
910 }),
911 );
912 }
913 return Effect.succeed(session);
914 }),
915 );
916 };
917
918 const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
919 authenticateRequest(request).pipe(
920 Effect.map(
921 (session) =>
922 ({
923 authenticated: true,
924 auth: descriptor,
925 ...authScopeResponse(session.scopes),
926 sessionMethod: session.method,
927 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
928 }) satisfies AuthSessionState,
929 ),
930 Effect.catchIf(isServerAuthCredentialError, () =>
931 Effect.succeed({
932 authenticated: false,
933 auth: descriptor,
934 } satisfies AuthSessionState),
935 ),
936 Effect.withSpan("EnvironmentAuth.getSessionState"),
937 );
938
939 const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = Effect.fn(
940 "EnvironmentAuth.createBrowserSession",
941 )(function* (credential, requestMetadata, previousSessionToken) {
942 if (devAuth?.matches(credential)) {
943 return yield* sessions.verify(credential).pipe(
944 mapSessionVerificationErrors,
945 Effect.flatMap((session) =>
946 DateTime.now.pipe(
947 Effect.map(
948 (now) =>
949 ({
950 response: {
951 authenticated: true,
952 ...authScopeResponse(session.scopes),
953 sessionMethod: session.method,
954 expiresAt: DateTime.toUtc(DateTime.add(now, { days: 30 })),
955 } satisfies AuthBrowserSessionResult,
956 sessionToken: credential,
957 cookieName: devAuth.cookieName,
958 expireNormalCookie: true,
959 }) satisfies BootstrapExchangeResult,
960 ),
961 ),
962 ),
963 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
964 );
965 }
966 const previousSession =
967 previousSessionToken === undefined
968 ? undefined
969 : yield* sessions.verify(previousSessionToken).pipe(
970 Effect.catchIf(SessionStore.isSessionCredentialInvalidError, () => Effect.void),
971 Effect.mapError((cause) => new ServerAuthSessionCredentialValidationError({ cause })),
972 );
973 const grant = yield* bootstrapCredentials
974 .consume(credential)
975 .pipe(Effect.mapError(toBootstrapExchangeError));
976 const session = yield* sessions
977 .issue({
978 method: "browser-session-cookie",
979 subject: grant.subject,
980 scopes: grant.scopes,
981 ...(previousSession?.method === "browser-session-cookie"
982 ? { replaceSessionId: previousSession.sessionId }
983 : {}),
984 client: {
985 ...requestMetadata,
986 ...(grant.label ? { label: grant.label } : {}),
987 },
988 })
989 .pipe(Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })));
990 return {
991 response: {
992 authenticated: true,
993 ...authScopeResponse(session.scopes),
994 sessionMethod: session.method,
995 expiresAt: DateTime.toUtc(session.expiresAt),
996 } satisfies AuthBrowserSessionResult,
997 sessionToken: session.token,
998 } satisfies BootstrapExchangeResult;
999 });
1000
1001 type ResolvedBootstrapGrant = Pick<
1002 PairingGrantStore.BootstrapGrant,
1003 "scopes" | "subject" | "label"
1004 > & {
1005 readonly method: PairingGrantStore.BootstrapGrant["method"] | "reusable-dev-token";
1006 };
1007 const resolveBootstrapGrant = (
1008 credential: string,
1009 input?: {
1010 readonly proofKeyThumbprint?: string;
1011 readonly requestedScopes?: ReadonlyArray<AuthEnvironmentScope>;
1012 readonly requiredScopes?: ReadonlyArray<AuthEnvironmentScope>;
1013 readonly allowedSubject?: string;
1014 /** Shown to approvers when the credential waits on T3 Connect device approval. */
1015 readonly requestMetadata?: AuthClientMetadata;
1016 },
1017 ): Effect.Effect<
1018 ResolvedBootstrapGrant,
1019 | ServerAuthInvalidCredentialError
1020 | ServerAuthInternalError
1021 | ServerAuthScopeNotGrantedError
1022 | ServerAuthConnectApprovalPendingError
1023 > => {
1024 if (!devAuth?.matches(credential)) {
1025 return bootstrapCredentials.consume(credential, input).pipe(
1026 Effect.catchTags({
1027 BootstrapCredentialConnectApprovalPendingError: (pending) =>
1028 recordConnectRequest(pending.pairingLinkId, input?.requestMetadata).pipe(
1029 Effect.andThen(Effect.fail(new ServerAuthConnectApprovalPendingError({}))),
1030 ),
1031 }),
1032 Effect.mapError((cause) =>
1033 cause._tag === "BootstrapCredentialScopeNotGrantedError"
1034 ? new ServerAuthScopeNotGrantedError({})
1035 : cause._tag === "ServerAuthConnectApprovalPendingError" ||
1036 cause._tag === "ServerAuthConnectDevicesError"
1037 ? cause
1038 : toBootstrapExchangeError(cause),
1039 ),
1040 );
1041 }
1042 return sessions.verify(credential).pipe(
1043 mapSessionVerificationErrors,
1044 Effect.filterOrFail(
1045 (session) =>
1046 input?.requiredScopes === undefined ||
1047 input.requiredScopes.every((scope) => session.scopes.includes(scope)),
1048 () => new ServerAuthScopeNotGrantedError({}),
1049 ),
1050 Effect.map(
1051 (session) =>
1052 ({
1053 method: "reusable-dev-token",
1054 scopes: session.scopes,
1055 subject: "reusable-dev-token-child",
1056 }) satisfies ResolvedBootstrapGrant,
1057 ),
1058 );
1059 };
1060
1061 // T3 Connect credential issuance, DPoP exchanges and device revocation take turns. Two mints
1062 // at once would open two requests with one code, and a revoke landing between an exchange
1063 // spending its credential and trusting the key would be undone by that exchange.
1064 const connectTrustLock = yield* Semaphore.make(1);
1065
1066 const toAccessTokenResult = (session: SessionStore.IssuedSession) =>
1067 DateTime.now.pipe(
1068 Effect.map(
1069 (now) =>
1070 ({
1071 access_token: session.token,
1072 issued_token_type: AuthAccessTokenType,
1073 token_type: session.proofKeyThumbprint ? "DPoP" : "Bearer",
1074 expires_in: Math.max(
1075 0,
1076 Math.floor((session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000),
1077 ),
1078 scope: encodeOAuthScope(session.scopes),
1079 }) satisfies AuthAccessTokenResult,
1080 ),
1081 );
1082
1083 const renewAccessToken: EnvironmentAuth["Service"]["renewAccessToken"] = Effect.fn(
1084 "EnvironmentAuth.renewAccessToken",
1085 )(function* (accessToken, proofKeyThumbprint, consumeProof) {
1086 const session = yield* sessions
1087 .renew(accessToken, {
1088 proofKeyThumbprint,
1089 ttl: RENEWABLE_ACCESS_TOKEN_TTL,
1090 renewalWindow: RENEWABLE_SESSION_WINDOW,
1091 consumeProof,
1092 })
1093 .pipe(
1094 Effect.mapError((cause) =>
1095 isServerAuthCredentialError(cause) || isServerAuthInternalError(cause)
1096 ? cause
1097 : toSessionVerificationError(cause),
1098 ),
1099 );
1100 return yield* toAccessTokenResult(session);
1101 });
1102
1103 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
1104 (credential, requestedScopes, requestMetadata, input) => {
1105 return resolveBootstrapGrant(credential, {
1106 ...input,
1107 requestMetadata,
1108 ...(requestedScopes !== undefined ? { requestedScopes } : {}),
1109 }).pipe(
1110 // Every T3 Connect key that gets in is remembered, so turning approval on later
1111 // keeps the devices already in use and lists them for review.
1112 Effect.tap((grant) =>
1113 grant.subject === CLOUD_CONNECT_SUBJECT && input?.proofKeyThumbprint
1114 ? bootstrapCredentials
1115 .trustConnectDevice(input.proofKeyThumbprint, requestMetadata)
1116 .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })))
1117 : Effect.void,
1118 ),
1119 Effect.flatMap((grant) =>
1120 Effect.gen(function* () {
1121 const grantedScopes =
1122 requestedScopes === undefined
1123 ? grant.scopes
1124 : [...new Set(requestedScopes)].filter((scope) => grant.scopes.includes(scope));
1125 if (grantedScopes.length === 0) {
1126 return yield* new ServerAuthScopeNotGrantedError({});
1127 }
1128 // Only plain pairing links renew. T3 Connect, CLI, desktop and peer sessions keep
1129 // their own lifetimes, so unlinking Connect or rotating a credential still cuts off.
1130 const renewable =
1131 input?.proofKeyThumbprint !== undefined &&
1132 grant.method === "one-time-token" &&
1133 grant.subject === PAIRING_LINK_SUBJECT;
1134 return yield* sessions
1135 .issue({
1136 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
1137 subject: grant.subject,
1138 scopes: grantedScopes,
1139 ...(input?.proofKeyThumbprint
1140 ? {
1141 proofKeyThumbprint: input.proofKeyThumbprint,
1142 ttl: renewable ? RENEWABLE_ACCESS_TOKEN_TTL : Duration.hours(1),
1143 }
1144 : {}),
1145 ...(renewable ? { renewalWindow: RENEWABLE_SESSION_WINDOW } : {}),
1146 replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap",
1147 client: {
1148 ...requestMetadata,
1149 ...(grant.label ? { label: grant.label } : {}),
1150 },
1151 })
1152 .pipe(
1153 Effect.mapError(
1154 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
1155 ),
1156 );
1157 }),
1158 ),
1159 Effect.flatMap(toAccessTokenResult),
1160 (exchange) =>
1161 input?.proofKeyThumbprint ? connectTrustLock.withPermits(1)(exchange) : exchange,
1162 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
1163 );
1164 };
1165
1166 const toPairingCredential = (issued: IssuedPairingLink): AuthPairingCredentialResult => ({
1167 id: issued.id,
1168 credential: issued.credential,
1169 ...(issued.label ? { label: issued.label } : {}),
1170 expiresAt: issued.expiresAt,
1171 });
1172
1173 const issuePairingLink = Effect.fn("EnvironmentAuth.issuePairingLink")(
1174 function* (input: Parameters<EnvironmentAuth["Service"]["createPairingLink"]>[0]) {
1175 const createdAt = yield* DateTime.now;
1176 const issued = yield* bootstrapCredentials.issueOneTimeToken({
1177 scopes: input?.scopes ?? AuthStandardClientScopes,
1178 subject: input?.subject ?? "one-time-token",
1179 ...(input?.ttl ? { ttl: input.ttl } : {}),
1180 ...(input?.label ? { label: input.label } : {}),
1181 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
1182 ...(input?.purpose ? { purpose: input.purpose } : {}),
1183 ...(input?.mcpApproval ? { mcpApproval: input.mcpApproval } : {}),
1184 ...(input?.requiresConnectApproval ? { requiresConnectApproval: true } : {}),
1185 });
1186 return {
1187 id: issued.id,
1188 credential: issued.credential,
1189 scopes: input?.scopes ?? AuthStandardClientScopes,
1190 subject: input?.subject ?? "one-time-token",
1191 ...(issued.label ? { label: issued.label } : {}),
1192 createdAt: DateTime.toUtc(createdAt),
1193 expiresAt: DateTime.toUtc(issued.expiresAt),
1194 } satisfies IssuedPairingLink;
1195 },
1196 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
1197 );
1198
1199 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
1200 "EnvironmentAuth.createPairingLink",
1201 )(function* (input) {
1202 // The startup link is for a browser on this machine; every other link lets a device pair.
1203 if (input?.purpose !== "startup" && !ManagedLimits.allowsRemoteClients(managedPolicy)) {
1204 return yield* ManagedLimits.refuseRemoteClients(
1205 managedPolicy,
1206 "so this server cannot create pairing links",
1207 );
1208 }
1209 return yield* issuePairingLink(input);
1210 });
1211
1212 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
1213 bootstrapCredentials.listActive().pipe(
1214 Effect.map((pairingLinks) => {
1215 const excludedSubjects = input?.excludeSubjects ?? [
1216 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1217 ];
1218 return pairingLinks
1219 .filter(
1220 (pairingLink) =>
1221 !excludedSubjects.includes(pairingLink.subject) &&
1222 !pairingLink.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX),
1223 )
1224 .map((link) => ({ ...link, ...authScopeResponse(link.scopes) }))
1225 .toSorted(
1226 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
1227 );
1228 }),
1229 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
1230 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
1231 );
1232
1233 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
1234 bootstrapCredentials.revoke(id).pipe(
1235 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
1236 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
1237 );
1238
1239 const recordConnectRequest = (pairingLinkId: string, client: AuthClientMetadata | undefined) =>
1240 client === undefined
1241 ? Effect.void
1242 : bootstrapCredentials
1243 .recordConnectRequestClient(pairingLinkId, client)
1244 .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1245
1246 const issueConnectCredential: EnvironmentAuth["Service"]["issueConnectCredential"] = Effect.fn(
1247 "EnvironmentAuth.issueConnectCredential",
1248 )(function* ({ proofKeyThumbprint, requireApproval }) {
1249 return yield* issueConnectCredentialLocked({ proofKeyThumbprint, requireApproval }).pipe(
1250 connectTrustLock.withPermits(1),
1251 );
1252 });
1253 // Untraced: the issueConnectCredential span above already covers it.
1254 const issueConnectCredentialLocked = Effect.fnUntraced(function* ({
1255 proofKeyThumbprint,
1256 requireApproval,
1257 }: Parameters<EnvironmentAuth["Service"]["issueConnectCredential"]>[0]) {
1258 const mustWait =
1259 requireApproval &&
1260 !(yield* bootstrapCredentials
1261 .isConnectDeviceTrusted(proofKeyThumbprint)
1262 .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause }))));
1263 if (mustWait) {
1264 const pending = yield* bootstrapCredentials
1265 .findPendingConnect(proofKeyThumbprint)
1266 .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1267 if (Option.isSome(pending)) {
1268 return { credential: pending.value.credential, expiresAt: pending.value.expiresAt };
1269 }
1270 }
1271 const issued = yield* createPairingLink({
1272 scopes: AuthStandardClientScopes,
1273 subject: CLOUD_CONNECT_SUBJECT,
1274 // Long enough for someone to notice the request and approve it.
1275 ttl: mustWait ? Duration.minutes(10) : Duration.minutes(2),
1276 label: "T3 Connect",
1277 proofKeyThumbprint,
1278 ...(mustWait ? { requiresConnectApproval: true } : {}),
1279 });
1280 return { credential: issued.credential, expiresAt: issued.expiresAt };
1281 });
1282
1283 const approveConnectDevice: EnvironmentAuth["Service"]["approveConnectDevice"] = (
1284 pairingLinkId,
1285 ) =>
1286 bootstrapCredentials.approveConnectRequest(pairingLinkId).pipe(
1287 Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })),
1288 Effect.withSpan("EnvironmentAuth.approveConnectDevice"),
1289 );
1290
1291 const connectRequestsShowingCode: EnvironmentAuth["Service"]["connectRequestsShowingCode"] =
1292 Effect.fn("EnvironmentAuth.connectRequestsShowingCode")(function* (verificationCode) {
1293 const wanted = normalizeVerificationCode(verificationCode);
1294 const links = yield* bootstrapCredentials
1295 .listActive()
1296 .pipe(Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })));
1297 return links.flatMap((link) =>
1298 link.connectDeviceRequest !== undefined &&
1299 normalizeVerificationCode(link.connectDeviceRequest.verificationCode) === wanted
1300 ? [link.id]
1301 : [],
1302 );
1303 });
1304
1305 const listConnectDevices: EnvironmentAuth["Service"]["listConnectDevices"] = () =>
1306 bootstrapCredentials.listConnectDevices().pipe(
1307 Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })),
1308 Effect.withSpan("EnvironmentAuth.listConnectDevices"),
1309 );
1310
1311 const revokeConnectDevice: EnvironmentAuth["Service"]["revokeConnectDevice"] = Effect.fn(
1312 "EnvironmentAuth.revokeConnectDevice",
1313 )(function* (proofKeyThumbprint) {
1314 return yield* Effect.gen(function* () {
1315 const removed = yield* bootstrapCredentials
1316 .revokeConnectDevice(proofKeyThumbprint)
1317 .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1318 const revokedSessions = yield* sessions
1319 .revokeByProofKey(proofKeyThumbprint)
1320 .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1321 return removed || revokedSessions > 0;
1322 }).pipe(connectTrustLock.withPermits(1));
1323 });
1324
1325 const connectDevicesShowingCode: EnvironmentAuth["Service"]["connectDevicesShowingCode"] =
1326 Effect.fn("EnvironmentAuth.connectDevicesShowingCode")(function* (verificationCode) {
1327 const wanted = normalizeVerificationCode(verificationCode);
1328 return (yield* listConnectDevices()).filter(
1329 (device) => normalizeVerificationCode(device.verificationCode) === wanted,
1330 );
1331 });
1332
1333 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
1334 sessions
1335 .issue({
1336 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1337 method: "bearer-access-token",
1338 scopes: input?.scopes ?? AuthStandardClientScopes,
1339 client: {
1340 ...(input?.label ? { label: input.label } : {}),
1341 deviceType: "bot",
1342 },
1343 ...(input?.ttl ? { ttl: input.ttl } : {}),
1344 })
1345 .pipe(
1346 Effect.map(
1347 (issued) =>
1348 ({
1349 sessionId: issued.sessionId,
1350 token: issued.token,
1351 method: "bearer-access-token",
1352 scopes: issued.scopes,
1353 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
1354 client: issued.client,
1355 expiresAt: DateTime.toUtc(issued.expiresAt),
1356 }) satisfies IssuedBearerSession,
1357 ),
1358 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1359 Effect.withSpan("EnvironmentAuth.issueSession"),
1360 );
1361
1362 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
1363 sessions.listActive().pipe(
1364 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
1365 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
1366 Effect.withSpan("EnvironmentAuth.listSessions"),
1367 );
1368
1369 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
1370 sessions.revoke(sessionId).pipe(
1371 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
1372 Effect.withSpan("EnvironmentAuth.revokeSession"),
1373 );
1374
1375 const revokeOtherSessionsExcept = (sessionId: AuthSessionId) =>
1376 sessions.revokeAllExcept(sessionId).pipe(
1377 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
1378 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
1379 );
1380
1381 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
1382 createPairingLink({
1383 scopes: input?.access
1384 ? mcpClientScopes(input.access)
1385 : (input?.scopes ?? AuthStandardClientScopes),
1386 subject:
1387 input?.purpose === "peer-link" && input.access
1388 ? `${PEER_LINK_PAIRING_SUBJECT_PREFIX}${input.access}`
1389 : "one-time-token",
1390 ...(input?.label ? { label: input.label } : {}),
1391 ...(input?.access && input.purpose !== "peer-link" ? { mcpApproval: input.access } : {}),
1392 }).pipe(
1393 Effect.map((issued) => ({
1394 ...toPairingCredential(issued),
1395 ...(input?.access ? { access: input.access } : {}),
1396 ...(input?.access && input.purpose === "peer-link" ? { purpose: input.purpose } : {}),
1397 })),
1398 Effect.withSpan("EnvironmentAuth.issuePairingCredential"),
1399 );
1400
1401 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
1402 () => {
1403 // Unguarded: startup already refused auth policies the managed policy leaves out.
1404 const fallback = issuePairingLink({
1405 scopes: AuthAdministrativeClientScopes,
1406 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
1407 purpose: "startup",
1408 }).pipe(Effect.map(toPairingCredential));
1409 if (!devAuth) {
1410 return fallback.pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
1411 }
1412 return sessions.verify(devAuth.credential).pipe(
1413 Effect.map(
1414 (session) =>
1415 ({
1416 id: session.sessionId,
1417 credential: devAuth.credential,
1418 label: "Reusable dev token",
1419 expiresAt: DateTime.toUtc(session.expiresAt ?? REUSABLE_DEV_SESSION_EXPIRES_AT),
1420 }) satisfies AuthPairingCredentialResult,
1421 ),
1422 Effect.catch((cause) =>
1423 SessionStore.isSessionCredentialInvalidError(cause)
1424 ? fallback
1425 : Effect.fail(new ServerAuthPairingLinkCreationError({ cause })),
1426 ),
1427 Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"),
1428 );
1429 };
1430
1431 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
1432 listSessions().pipe(
1433 Effect.map((clientSessions) =>
1434 clientSessions.map((clientSession): AuthClientSession => ({
1435 ...clientSession,
1436 ...authScopeResponse(clientSession.scopes),
1437 current: clientSession.sessionId === currentSessionId,
1438 })),
1439 ),
1440 Effect.withSpan("EnvironmentAuth.listClientSessions"),
1441 );
1442
1443 const proofKeyOf = (sessionId: AuthSessionId) =>
1444 sessions
1445 .proofKeyThumbprintOf(sessionId)
1446 .pipe(Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })));
1447
1448 const revokeClient: EnvironmentAuth["Service"]["revokeClient"] = Effect.fn(
1449 "EnvironmentAuth.revokeClient",
1450 )(function* (sessionId) {
1451 // A T3 Connect device would otherwise mint itself a new session right away.
1452 return yield* Option.match(yield* proofKeyOf(sessionId), {
1453 onNone: () => revokeSession(sessionId),
1454 onSome: revokeConnectDevice,
1455 });
1456 });
1457
1458 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
1459 "EnvironmentAuth.revokeClientSession",
1460 )(function* (currentSessionId, targetSessionId) {
1461 if (currentSessionId === targetSessionId) {
1462 return yield* new ServerAuthForbiddenOperationError({});
1463 }
1464 const targetProofKey = Option.getOrUndefined(yield* proofKeyOf(targetSessionId));
1465 // Revoking the caller's own device would cut off the caller too.
1466 if (
1467 targetProofKey !== undefined &&
1468 Option.getOrUndefined(yield* proofKeyOf(currentSessionId)) === targetProofKey
1469 ) {
1470 return yield* revokeSession(targetSessionId);
1471 }
1472 return yield* revokeClient(targetSessionId);
1473 });
1474
1475 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] =
1476 Effect.fn("EnvironmentAuth.revokeOtherClientSessions")(function* (currentSessionId) {
1477 const currentProofKey = yield* sessions
1478 .proofKeyThumbprintOf(currentSessionId)
1479 .pipe(Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })));
1480 return yield* Effect.gen(function* () {
1481 yield* bootstrapCredentials
1482 .revokeConnectDevicesExcept(Option.getOrNull(currentProofKey))
1483 .pipe(Effect.mapError((cause) => new ServerAuthConnectDevicesError({ cause })));
1484 return yield* revokeOtherSessionsExcept(currentSessionId);
1485 }).pipe(connectTrustLock.withPermits(1));
1486 });
1487
1488 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
1489 issueStartupPairingCredential().pipe(
1490 Effect.map((issued) => {
1491 const url = new URL(baseUrl);
1492 url.pathname = "/pair";
1493 url.searchParams.delete("token");
1494 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
1495 return url.toString();
1496 }),
1497 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
1498 );
1499
1500 // Only the RPC socket's ticket is bound to the client's proof key. The media
1501 // routes reuse one ticket across <img>, EventSource and several sockets, and
1502 // each of those would need its own single-use proof.
1503 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (
1504 session,
1505 input,
1506 ) =>
1507 sessions
1508 .issueWebSocketToken(session.sessionId, {
1509 ...(input?.use ? { audience: input.use } : {}),
1510 ...(input?.use === "rpc" && session.proofKeyThumbprint
1511 ? { proofKeyThumbprint: session.proofKeyThumbprint }
1512 : {}),
1513 })
1514 .pipe(
1515 Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
1516 Effect.map(
1517 (issued) =>
1518 ({
1519 ticket: Redacted.make(issued.token),
1520 expiresAt: DateTime.toUtc(issued.expiresAt),
1521 }) satisfies AuthWebSocketTicketResult,
1522 ),
1523 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
1524 );
1525
1526 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
1527 request,
1528 ) =>
1529 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
1530
1531 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
1532 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request, use) {
1533 const url = requestUrl(request);
1534 if (Option.isSome(url)) {
1535 const query = yield* decodeWebSocketUpgradeQuery(
1536 Object.fromEntries(url.value.searchParams),
1537 ).pipe(Effect.orDie);
1538 const websocketTicket = query.wsTicket && Redacted.value(query.wsTicket);
1539 if (websocketTicket && websocketTicket.trim().length > 0) {
1540 const session = yield* sessions
1541 .verifyWebSocketToken(websocketTicket)
1542 .pipe(mapSessionVerificationErrors, Effect.flatMap(rejectMcpClientAudience));
1543 if (session.audience !== undefined && session.audience !== use) {
1544 return yield* new ServerAuthInvalidCredentialError({
1545 diagnostic: `WebSocket ticket was issued for the ${session.audience} route.`,
1546 });
1547 }
1548 if (session.proofKeyThumbprint) {
1549 // WebSocket clients cannot set headers, so the proof travels in the query.
1550 // The proof hashes the ticket; consuming its jti prevents replay after first use.
1551 // Only encrypted transport prevents an active interceptor from racing that use.
1552 const proof = request.headers.dpop ?? (query.dpop && Redacted.value(query.dpop));
1553 if (!proof) {
1554 return yield* new ServerAuthInvalidCredentialError({
1555 diagnostic: "DPoP-bound WebSocket ticket requires a DPoP proof.",
1556 dpopFailureReason: "invalid_proof",
1557 });
1558 }
1559 yield* verifyRequestDpopProof({
1560 request,
1561 proof,
1562 expectedThumbprint: session.proofKeyThumbprint,
1563 expectedAccessToken: websocketTicket,
1564 }).pipe(
1565 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
1566 Effect.provideService(Digest.Digest, digest),
1567 );
1568 }
1569 return {
1570 sessionId: session.sessionId,
1571 subject: session.subject,
1572 method: session.method,
1573 scopes: session.scopes,
1574 ...(session.proofKeyThumbprint
1575 ? { proofKeyThumbprint: session.proofKeyThumbprint }
1576 : {}),
1577 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
1578 };
1579 }
1580 }
1581
1582 return yield* authenticateRequest(request);
1583 });
1584
1585 /** The expiry of a verified peer link session, moved out when this use finds it a step short. */
1586 const renewPeerLinkSession = Effect.fnUntraced(function* (
1587 sessionId: AuthSessionId,
1588 expiresAt: DateTime.DateTime,
1589 ) {
1590 const now = yield* DateTime.now;
1591 const renewed = DateTime.add(now, {
1592 milliseconds: Duration.toMillis(MCP_CLIENT_SESSION_TTL),
1593 });
1594 if (DateTime.distance(expiresAt, renewed).pipe(Duration.isLessThan(PEER_LINK_RENEWAL_STEP))) {
1595 return DateTime.toUtc(expiresAt);
1596 }
1597 const current = yield* sessions
1598 .extend(sessionId, renewed, PEER_LINK_RENEWAL_STEP)
1599 .pipe(mapSessionVerificationErrors);
1600 // A revoke can land between the verification and the update.
1601 if (Option.isNone(current)) {
1602 return yield* new ServerAuthInvalidCredentialError({
1603 diagnostic: "The peer link session ended before it could be renewed.",
1604 });
1605 }
1606 return current.value;
1607 });
1608
1609 const authenticateMcpClient: EnvironmentAuth["Service"]["authenticateMcpClient"] = (request) => {
1610 const token = parseBearerToken(request);
1611 if (token === null) return Effect.fail(new ServerAuthMissingCredentialError({}));
1612 return sessions.verify(token).pipe(
1613 mapSessionVerificationErrors,
1614 Effect.flatMap(
1615 Effect.fnUntraced(function* (session) {
1616 if (session.subject !== MCP_CLIENT_SUBJECT || session.method !== "bearer-access-token") {
1617 return yield* new ServerAuthInvalidCredentialError({
1618 diagnostic: "Only MCP client sessions are accepted here.",
1619 });
1620 }
1621 const client = {
1622 sessionId: session.sessionId,
1623 label: session.client.label ?? "MCP client",
1624 access: session.scopes.includes(AuthOrchestrationOperateScope)
1625 ? (session.runtimeModeCeiling ?? "approval-required")
1626 : "read-only",
1627 peerLink: session.peerLink === true,
1628 } satisfies McpClientSession;
1629 if (session.peerLink !== true || session.expiresAt === undefined) return client;
1630 return {
1631 ...client,
1632 linkExpiresAt: yield* renewPeerLinkSession(session.sessionId, session.expiresAt),
1633 } satisfies McpClientSession;
1634 }),
1635 ),
1636 Effect.withSpan("EnvironmentAuth.authenticateMcpClient"),
1637 );
1638 };
1639
1640 const issueMcpClientSession: EnvironmentAuth["Service"]["issueMcpClientSession"] = (input) =>
1641 sessions
1642 .issue({
1643 subject: MCP_CLIENT_SUBJECT,
1644 method: "bearer-access-token",
1645 scopes: mcpClientScopes(input.access),
1646 ttl: MCP_CLIENT_SESSION_TTL,
1647 ...(input.access === "read-only" ? {} : { runtimeModeCeiling: input.access }),
1648 peerLink: input.peerLink,
1649 client: { ...input.client, label: input.label, deviceType: "bot" },
1650 })
1651 .pipe(
1652 Effect.map((issued) => ({
1653 sessionId: issued.sessionId,
1654 token: issued.token,
1655 expiresAt: issued.expiresAt,
1656 })),
1657 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
1658 Effect.withSpan("EnvironmentAuth.issueMcpClientSession"),
1659 );
1660
1661 const consumeMcpApprovalCode: EnvironmentAuth["Service"]["consumeMcpApprovalCode"] = (
1662 code,
1663 access,
1664 peerLink = false,
1665 ) =>
1666 resolveBootstrapGrant(code.trim(), {
1667 requiredScopes: mcpClientScopes(access),
1668 allowedSubject: `${peerLink ? PEER_LINK_PAIRING_SUBJECT_PREFIX : MCP_APPROVAL_SUBJECT_PREFIX}${access}`,
1669 }).pipe(
1670 Effect.catchTags({
1671 ServerAuthInvalidCredentialError: () =>
1672 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1673 ServerAuthConnectApprovalPendingError: () =>
1674 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "unknown_or_used" })),
1675 ServerAuthScopeNotGrantedError: () =>
1676 Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "insufficient_scope" })),
1677 }),
1678 Effect.flatMap((grant) =>
1679 grant.method !== "one-time-token" && grant.method !== "reusable-dev-token"
1680 ? Effect.fail(new ServerAuthMcpApprovalCodeError({ reason: "not_a_pairing_code" }))
1681 : Effect.succeed(mcpApprovalLevel(grant.subject) ?? access),
1682 ),
1683 Effect.withSpan("EnvironmentAuth.consumeMcpApprovalCode"),
1684 );
1685
1686 yield* revokePairedClientsThePolicyDisallows(managedPolicy, {
1687 sessions,
1688 pairingLinks: bootstrapCredentials,
1689 });
1690
1691 return EnvironmentAuth.of({
1692 getDescriptor: Effect.fn("EnvironmentAuth.getDescriptor")(function () {
1693 return Effect.succeed(descriptor);
1694 }),
1695 getSessionState,
1696 createBrowserSession,
1697 exchangeBootstrapCredentialForAccessToken,
1698 renewAccessToken,
1699 createPairingLink,
1700 issueConnectCredential,
1701 approveConnectDevice,
1702 connectRequestsShowingCode,
1703 listConnectDevices,
1704 revokeConnectDevice,
1705 connectDevicesShowingCode,
1706 issuePairingCredential,
1707 issueStartupPairingCredential,
1708 listPairingLinks,
1709 revokePairingLink,
1710 issueSession,
1711 listSessions,
1712 revokeSession,
1713 listClientSessions,
1714 revokeClient,
1715 revokeClientSession,
1716 revokeOtherClientSessions,
1717 authenticateHttpRequest,
1718 authenticateWebSocketUpgrade,
1719 issueWebSocketTicket,
1720 issueStartupPairingUrl,
1721 authenticateMcpClient,
1722 issueMcpClientSession,
1723 consumeMcpApprovalCode,
1724 });
1725 });
1726
1727 const isMcpClientAccess = Schema.is(AuthMcpClientAccess);
1728
1729 const normalizeVerificationCode = (code: string) => code.toUpperCase().replace(/[^0-9A-Z]/g, "");
1730
1731 /** The level an approval code's subject names, or undefined for any other code. */
1732 const mcpApprovalLevel = (subject: string): AuthMcpClientAccess | undefined => {
1733 const level = subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)
1734 ? subject.slice(MCP_APPROVAL_SUBJECT_PREFIX.length)
1735 : undefined;
1736 return isMcpClientAccess(level) ? level : undefined;
1737 };
1738
1739 /** Subjects of sessions and links a pairing link created, keyed by how the client paired. */
1740 const LINK_PAIRED_SUBJECTS = { link: "one-time-token", connect: CLOUD_CONNECT_SUBJECT } as const;
1741
1742 /**
1743 * Revokes sessions and unused links from pairing the policy no longer allows, so a policy rolled
1744 * out to a machine that already had phones paired takes effect on the next start.
1745 */
1746 const revokePairedClientsThePolicyDisallows = Effect.fn(
1747 "EnvironmentAuth.revokePairedClientsThePolicyDisallows",
1748 )(function* (
1749 policy: ManagedPolicy.ManagedPolicy["Service"],
1750 stores: {
1751 readonly sessions: SessionStore.SessionStore["Service"];
1752 readonly pairingLinks: PairingGrantStore.PairingGrantStore["Service"];
1753 },
1754 ) {
1755 const remoteAllowed = ManagedLimits.allowsRemoteClients(policy);
1756 const disallowed = new Set<string>();
1757 if (!remoteAllowed) disallowed.add(LINK_PAIRED_SUBJECTS.link);
1758 if (!ManagedLimits.allowsConnect(policy)) disallowed.add(LINK_PAIRED_SUBJECTS.connect);
1759 if (disallowed.size === 0) return;
1760 const sessions = (yield* stores.sessions.listActive()).filter(
1761 (session) =>
1762 disallowed.has(session.subject) ||
1763 // The startup link also pairs browsers on this machine; only a device elsewhere goes.
1764 (!remoteAllowed &&
1765 session.subject === INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT &&
1766 session.client.ipAddress !== undefined &&
1767 !isLocalLoopbackHost(session.client.ipAddress)),
1768 );
1769 const links = (yield* stores.pairingLinks.listActive()).filter(
1770 (link) =>
1771 disallowed.has(link.subject) ||
1772 // Approval codes let an agent elsewhere sign in, as plain codes do.
1773 (!remoteAllowed && link.subject.startsWith(MCP_APPROVAL_SUBJECT_PREFIX)),
1774 );
1775 yield* Effect.forEach(sessions, (session) => stores.sessions.revoke(session.sessionId), {
1776 discard: true,
1777 });
1778 yield* Effect.forEach(links, (link) => stores.pairingLinks.revoke(link.id), { discard: true });
1779 if (sessions.length > 0 || links.length > 0) {
1780 yield* Effect.logInfo("Revoked clients the managed policy does not allow.", {
1781 sessions: sessions.length,
1782 pairingLinks: links.length,
1783 });
1784 }
1785 });
1786
1787 export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1788 Layer.provideMerge(PairingGrantStore.layer),
1789 Layer.provideMerge(SessionStore.layer),
1790 Layer.provideMerge(EnvironmentAuthPolicy.layer),
1791 );
1792
1793 const layerStorage = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistence.layerCliConfig);
1794
1795 export const layerRuntime = layer.pipe(
1796 Layer.provideMerge(ManagedPolicy.layer),
1797 Layer.provideMerge(layerStorage),
1798 Layer.provideMerge(ServerEnvironment.layerIdentity),
1799 );