Open History to see the last commit
1import {
2 AuthAccessTokenType,
3 AuthAccessWriteScope,
4 AuthAdministrativeScopes,
5 AuthStandardClientScopes,
6 type AuthAccessTokenResult,
7 type AuthBrowserSessionResult,
8 type AuthClientMetadata,
9 type AuthClientSession,
10 type AuthCreatePairingCredentialInput,
11 type AuthEnvironmentScope,
12 type AuthPairingLink,
13 type AuthPairingCredentialResult,
14 type AuthSessionId,
15 type AuthSessionState,
16 type ServerAuthDescriptor,
17 type ServerAuthSessionMethod,
18 type AuthWebSocketTicketResult,
19} from "@v12/contracts";
20import { encodeOAuthScope } from "@v12/shared/oauthScope";
21import * as Context from "effect/Context";
22import * as Crypto from "effect/Crypto";
23import * as DateTime from "effect/DateTime";
24import * as Duration from "effect/Duration";
25import * as Effect from "effect/Effect";
26import * as Layer from "effect/Layer";
27import * as Option from "effect/Option";
28import * as Schema from "effect/Schema";
29import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
30
31import * as EnvironmentAuthPolicy from "./EnvironmentAuthPolicy.ts";
32import * as PairingGrantStore from "./PairingGrantStore.ts";
33import * as ServerSecretStore from "./ServerSecretStore.ts";
34import * as SessionStore from "./SessionStore.ts";
35import { verifyRequestDpopProof } from "./dpop.ts";
36import { layerConfig as SqlitePersistenceLayer } from "../persistence/Layers/Sqlite.ts";
37
38export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
39export const INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT = "administrative-bootstrap";
40
41export interface IssuedPairingLink {
42 readonly id: string;
43 readonly credential: string;
44 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
45 readonly subject: string;
46 readonly label?: string;
47 readonly createdAt: DateTime.Utc;
48 readonly expiresAt: DateTime.Utc;
49}
50
51export interface IssuedBearerSession {
52 readonly sessionId: AuthSessionId;
53 readonly token: string;
54 readonly method: "bearer-access-token";
55 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
56 readonly subject: string;
57 readonly client: AuthClientMetadata;
58 readonly expiresAt: DateTime.Utc;
59}
60
61export interface AuthenticatedSession {
62 readonly sessionId: AuthSessionId;
63 readonly subject: string;
64 readonly method: ServerAuthSessionMethod;
65 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
66 readonly proofKeyThumbprint?: string;
67 readonly expiresAt?: DateTime.DateTime;
68}
69
70const serverAuthInternalErrorContext = {
71 cause: Schema.Defect(),
72};
73
74export class ServerAuthBootstrapCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthBootstrapCredentialValidationError>()(
75 "ServerAuthBootstrapCredentialValidationError",
76 {
77 ...serverAuthInternalErrorContext,
78 },
79) {
80 override get message(): string {
81 return "Failed to validate bootstrap credential.";
82 }
83}
84
85export class ServerAuthSessionCredentialValidationError extends Schema.TaggedErrorClass<ServerAuthSessionCredentialValidationError>()(
86 "ServerAuthSessionCredentialValidationError",
87 {
88 ...serverAuthInternalErrorContext,
89 },
90) {
91 override get message(): string {
92 return "Failed to validate session credential.";
93 }
94}
95
96export class ServerAuthAuthenticatedSessionIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedSessionIssueError>()(
97 "ServerAuthAuthenticatedSessionIssueError",
98 {
99 ...serverAuthInternalErrorContext,
100 },
101) {
102 override get message(): string {
103 return "Failed to issue authenticated session.";
104 }
105}
106
107export class ServerAuthAuthenticatedAccessTokenIssueError extends Schema.TaggedErrorClass<ServerAuthAuthenticatedAccessTokenIssueError>()(
108 "ServerAuthAuthenticatedAccessTokenIssueError",
109 {
110 ...serverAuthInternalErrorContext,
111 },
112) {
113 override get message(): string {
114 return "Failed to issue authenticated access token.";
115 }
116}
117
118export class ServerAuthPairingLinkCreationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkCreationError>()(
119 "ServerAuthPairingLinkCreationError",
120 {
121 ...serverAuthInternalErrorContext,
122 },
123) {
124 override get message(): string {
125 return "Failed to create pairing link.";
126 }
127}
128
129export class ServerAuthPairingLinksListError extends Schema.TaggedErrorClass<ServerAuthPairingLinksListError>()(
130 "ServerAuthPairingLinksListError",
131 {
132 ...serverAuthInternalErrorContext,
133 },
134) {
135 override get message(): string {
136 return "Failed to list pairing links.";
137 }
138}
139
140export class ServerAuthPairingLinkRevocationError extends Schema.TaggedErrorClass<ServerAuthPairingLinkRevocationError>()(
141 "ServerAuthPairingLinkRevocationError",
142 {
143 ...serverAuthInternalErrorContext,
144 },
145) {
146 override get message(): string {
147 return "Failed to revoke pairing link.";
148 }
149}
150
151export class ServerAuthSessionTokenIssueError extends Schema.TaggedErrorClass<ServerAuthSessionTokenIssueError>()(
152 "ServerAuthSessionTokenIssueError",
153 {
154 ...serverAuthInternalErrorContext,
155 },
156) {
157 override get message(): string {
158 return "Failed to issue session token.";
159 }
160}
161
162export class ServerAuthSessionsListError extends Schema.TaggedErrorClass<ServerAuthSessionsListError>()(
163 "ServerAuthSessionsListError",
164 {
165 ...serverAuthInternalErrorContext,
166 },
167) {
168 override get message(): string {
169 return "Failed to list sessions.";
170 }
171}
172
173export class ServerAuthSessionRevocationError extends Schema.TaggedErrorClass<ServerAuthSessionRevocationError>()(
174 "ServerAuthSessionRevocationError",
175 {
176 ...serverAuthInternalErrorContext,
177 },
178) {
179 override get message(): string {
180 return "Failed to revoke session.";
181 }
182}
183
184export class ServerAuthOtherSessionsRevocationError extends Schema.TaggedErrorClass<ServerAuthOtherSessionsRevocationError>()(
185 "ServerAuthOtherSessionsRevocationError",
186 {
187 ...serverAuthInternalErrorContext,
188 },
189) {
190 override get message(): string {
191 return "Failed to revoke other sessions.";
192 }
193}
194
195export class ServerAuthWebSocketTokenIssueError extends Schema.TaggedErrorClass<ServerAuthWebSocketTokenIssueError>()(
196 "ServerAuthWebSocketTokenIssueError",
197 {
198 ...serverAuthInternalErrorContext,
199 },
200) {
201 override get message(): string {
202 return "Failed to issue websocket token.";
203 }
204}
205
206export class ServerAuthDpopReplayStateRecordError extends Schema.TaggedErrorClass<ServerAuthDpopReplayStateRecordError>()(
207 "ServerAuthDpopReplayStateRecordError",
208 {
209 ...serverAuthInternalErrorContext,
210 },
211) {
212 override get message(): string {
213 return "Failed to record DPoP proof replay state.";
214 }
215}
216
217export class ServerAuthDpopReplayKeyCalculationError extends Schema.TaggedErrorClass<ServerAuthDpopReplayKeyCalculationError>()(
218 "ServerAuthDpopReplayKeyCalculationError",
219 {
220 ...serverAuthInternalErrorContext,
221 },
222) {
223 override get message(): string {
224 return "Failed to calculate DPoP replay key.";
225 }
226}
227
228export class ServerAuthLinkedCloudAccountVerificationError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountVerificationError>()(
229 "ServerAuthLinkedCloudAccountVerificationError",
230 {
231 ...serverAuthInternalErrorContext,
232 },
233) {
234 override get message(): string {
235 return "Could not verify the linked cloud account.";
236 }
237}
238
239export class ServerAuthLinkedCloudAccountReadError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountReadError>()(
240 "ServerAuthLinkedCloudAccountReadError",
241 {
242 ...serverAuthInternalErrorContext,
243 },
244) {
245 override get message(): string {
246 return "Could not read the linked cloud account.";
247 }
248}
249
250export class ServerAuthLinkedCloudAccountMissingError extends Schema.TaggedErrorClass<ServerAuthLinkedCloudAccountMissingError>()(
251 "ServerAuthLinkedCloudAccountMissingError",
252 {},
253) {
254 override get message(): string {
255 return "Cloud linked user is not installed for this environment.";
256 }
257}
258
259export class ServerAuthCloudLinkJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudLinkJwtSigningError>()(
260 "ServerAuthCloudLinkJwtSigningError",
261 {
262 ...serverAuthInternalErrorContext,
263 },
264) {
265 override get message(): string {
266 return "Failed to sign cloud link JWT.";
267 }
268}
269
270export class ServerAuthCloudMintPublicKeyMissingError extends Schema.TaggedErrorClass<ServerAuthCloudMintPublicKeyMissingError>()(
271 "ServerAuthCloudMintPublicKeyMissingError",
272 {},
273) {
274 override get message(): string {
275 return "Cloud mint public key is not installed for this environment.";
276 }
277}
278
279export class ServerAuthCloudRelayIssuerMissingError extends Schema.TaggedErrorClass<ServerAuthCloudRelayIssuerMissingError>()(
280 "ServerAuthCloudRelayIssuerMissingError",
281 {},
282) {
283 override get message(): string {
284 return "Cloud relay issuer is not installed for this environment.";
285 }
286}
287
288export class ServerAuthCloudHealthJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudHealthJwtSigningError>()(
289 "ServerAuthCloudHealthJwtSigningError",
290 {
291 ...serverAuthInternalErrorContext,
292 },
293) {
294 override get message(): string {
295 return "Failed to sign cloud health JWT.";
296 }
297}
298
299export class ServerAuthCloudMintJwtSigningError extends Schema.TaggedErrorClass<ServerAuthCloudMintJwtSigningError>()(
300 "ServerAuthCloudMintJwtSigningError",
301 {
302 ...serverAuthInternalErrorContext,
303 },
304) {
305 override get message(): string {
306 return "Failed to sign cloud mint JWT.";
307 }
308}
309
310export const ServerAuthInternalError = Schema.Union([
311 ServerAuthBootstrapCredentialValidationError,
312 ServerAuthSessionCredentialValidationError,
313 ServerAuthAuthenticatedSessionIssueError,
314 ServerAuthAuthenticatedAccessTokenIssueError,
315 ServerAuthPairingLinkCreationError,
316 ServerAuthPairingLinksListError,
317 ServerAuthPairingLinkRevocationError,
318 ServerAuthSessionTokenIssueError,
319 ServerAuthSessionsListError,
320 ServerAuthSessionRevocationError,
321 ServerAuthOtherSessionsRevocationError,
322 ServerAuthWebSocketTokenIssueError,
323 ServerAuthDpopReplayStateRecordError,
324 ServerAuthDpopReplayKeyCalculationError,
325 ServerAuthLinkedCloudAccountVerificationError,
326 ServerAuthLinkedCloudAccountReadError,
327 ServerAuthLinkedCloudAccountMissingError,
328 ServerAuthCloudLinkJwtSigningError,
329 ServerAuthCloudMintPublicKeyMissingError,
330 ServerAuthCloudRelayIssuerMissingError,
331 ServerAuthCloudHealthJwtSigningError,
332 ServerAuthCloudMintJwtSigningError,
333]);
334export type ServerAuthInternalError = typeof ServerAuthInternalError.Type;
335export const isServerAuthInternalError = Schema.is(ServerAuthInternalError);
336
337export class ServerAuthMissingCredentialError extends Schema.TaggedErrorClass<ServerAuthMissingCredentialError>()(
338 "ServerAuthMissingCredentialError",
339 {},
340) {
341 override get message(): string {
342 return "Server authentication credential is missing.";
343 }
344}
345
346export class ServerAuthInvalidCredentialError extends Schema.TaggedErrorClass<ServerAuthInvalidCredentialError>()(
347 "ServerAuthInvalidCredentialError",
348 {
349 diagnostic: Schema.optional(Schema.String),
350 cause: Schema.optional(Schema.Defect()),
351 },
352) {
353 override get message(): string {
354 return "Server authentication credential is invalid.";
355 }
356}
357
358export const ServerAuthCredentialError = Schema.Union([
359 ServerAuthMissingCredentialError,
360 ServerAuthInvalidCredentialError,
361]);
362export type ServerAuthCredentialError = typeof ServerAuthCredentialError.Type;
363export const isServerAuthCredentialError = Schema.is(ServerAuthCredentialError);
364export const serverAuthCredentialReason = (
365 error: ServerAuthCredentialError,
366): "missing_credential" | "invalid_credential" =>
367 error._tag === "ServerAuthMissingCredentialError" ? "missing_credential" : "invalid_credential";
368
369export class ServerAuthInvalidScopeError extends Schema.TaggedErrorClass<ServerAuthInvalidScopeError>()(
370 "ServerAuthInvalidScopeError",
371 {},
372) {
373 override get message(): string {
374 return "The requested authentication scope is invalid.";
375 }
376}
377
378export class ServerAuthScopeNotGrantedError extends Schema.TaggedErrorClass<ServerAuthScopeNotGrantedError>()(
379 "ServerAuthScopeNotGrantedError",
380 {},
381) {
382 override get message(): string {
383 return "The requested authentication scope was not granted.";
384 }
385}
386
387export const ServerAuthInvalidRequestError = Schema.Union([
388 ServerAuthInvalidScopeError,
389 ServerAuthScopeNotGrantedError,
390]);
391export type ServerAuthInvalidRequestError = typeof ServerAuthInvalidRequestError.Type;
392export const isServerAuthInvalidRequestError = Schema.is(ServerAuthInvalidRequestError);
393export const serverAuthInvalidRequestReason = (
394 error: ServerAuthInvalidRequestError,
395): "invalid_scope" | "scope_not_granted" =>
396 error._tag === "ServerAuthInvalidScopeError" ? "invalid_scope" : "scope_not_granted";
397
398export class ServerAuthForbiddenOperationError extends Schema.TaggedErrorClass<ServerAuthForbiddenOperationError>()(
399 "ServerAuthForbiddenOperationError",
400 {},
401) {
402 override get message(): string {
403 return "The current authentication session cannot revoke itself.";
404 }
405}
406
407export class EnvironmentAuth extends Context.Service<
408 EnvironmentAuth,
409 {
410 readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
411 readonly getSessionState: (
412 request: HttpServerRequest.HttpServerRequest,
413 ) => Effect.Effect<AuthSessionState, ServerAuthInternalError>;
414 readonly createBrowserSession: (
415 credential: string,
416 requestMetadata: AuthClientMetadata,
417 ) => Effect.Effect<
418 {
419 readonly response: AuthBrowserSessionResult;
420 readonly sessionToken: string;
421 },
422 ServerAuthInvalidCredentialError | ServerAuthInternalError
423 >;
424 readonly exchangeBootstrapCredentialForAccessToken: (
425 credential: string,
426 requestedScopes: ReadonlyArray<AuthEnvironmentScope> | undefined,
427 requestMetadata: AuthClientMetadata,
428 input?: {
429 readonly proofKeyThumbprint?: string;
430 },
431 ) => Effect.Effect<
432 AuthAccessTokenResult,
433 ServerAuthInvalidCredentialError | ServerAuthInvalidRequestError | ServerAuthInternalError
434 >;
435 readonly createPairingLink: (input?: {
436 readonly ttl?: Duration.Duration;
437 readonly label?: string;
438 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
439 readonly subject?: string;
440 readonly proofKeyThumbprint?: string;
441 }) => Effect.Effect<IssuedPairingLink, ServerAuthInternalError>;
442 readonly issuePairingCredential: (
443 input?: AuthCreatePairingCredentialInput,
444 ) => Effect.Effect<AuthPairingCredentialResult, ServerAuthInternalError>;
445 readonly issueStartupPairingCredential: () => Effect.Effect<
446 AuthPairingCredentialResult,
447 ServerAuthInternalError
448 >;
449 readonly listPairingLinks: (input?: {
450 readonly excludeSubjects?: ReadonlyArray<string>;
451 }) => Effect.Effect<ReadonlyArray<AuthPairingLink>, ServerAuthInternalError>;
452 readonly revokePairingLink: (id: string) => Effect.Effect<boolean, ServerAuthInternalError>;
453 readonly issueSession: (input?: {
454 readonly ttl?: Duration.Duration;
455 readonly subject?: string;
456 readonly scopes?: ReadonlyArray<AuthEnvironmentScope>;
457 readonly label?: string;
458 }) => Effect.Effect<IssuedBearerSession, ServerAuthInternalError>;
459 readonly listSessions: () => Effect.Effect<
460 ReadonlyArray<AuthClientSession>,
461 ServerAuthInternalError
462 >;
463 readonly revokeSession: (
464 sessionId: AuthSessionId,
465 ) => Effect.Effect<boolean, ServerAuthInternalError>;
466 readonly revokeOtherSessionsExcept: (
467 sessionId: AuthSessionId,
468 ) => Effect.Effect<number, ServerAuthInternalError>;
469 readonly listClientSessions: (
470 currentSessionId: AuthSessionId,
471 ) => Effect.Effect<ReadonlyArray<AuthClientSession>, ServerAuthInternalError>;
472 readonly revokeClientSession: (
473 currentSessionId: AuthSessionId,
474 targetSessionId: AuthSessionId,
475 ) => Effect.Effect<boolean, ServerAuthForbiddenOperationError | ServerAuthInternalError>;
476 readonly revokeOtherClientSessions: (
477 currentSessionId: AuthSessionId,
478 ) => Effect.Effect<number, ServerAuthInternalError>;
479 readonly authenticateHttpRequest: (
480 request: HttpServerRequest.HttpServerRequest,
481 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
482 readonly authenticateWebSocketUpgrade: (
483 request: HttpServerRequest.HttpServerRequest,
484 ) => Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError>;
485 readonly issueWebSocketTicket: (
486 session: Pick<AuthenticatedSession, "sessionId">,
487 ) => Effect.Effect<AuthWebSocketTicketResult, ServerAuthInternalError>;
488 readonly issueStartupPairingUrl: (
489 baseUrl: string,
490 ) => Effect.Effect<string, ServerAuthInternalError>;
491 }
492>()("v12/auth/EnvironmentAuth") {}
493
494type BootstrapExchangeResult = {
495 readonly response: AuthBrowserSessionResult;
496 readonly sessionToken: string;
497};
498
499const AUTHORIZATION_PREFIX = "Bearer ";
500const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
501const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
502
503const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
504 const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
505 const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
506 if (leftCanManage !== rightCanManage) {
507 return leftCanManage ? -1 : 1;
508 }
509 if (left.connected !== right.connected) {
510 return left.connected ? -1 : 1;
511 }
512 return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds;
513};
514
515export function toBootstrapExchangeError(
516 cause: PairingGrantStore.BootstrapCredentialError,
517): ServerAuthInvalidCredentialError | ServerAuthInternalError {
518 if (PairingGrantStore.isBootstrapCredentialInternalError(cause)) {
519 return new ServerAuthBootstrapCredentialValidationError({ cause });
520 }
521
522 return new ServerAuthInvalidCredentialError({
523 cause,
524 });
525}
526
527const mapSessionVerificationErrors = <A, R>(
528 effect: Effect.Effect<A, SessionStore.SessionCredentialError, R>,
529): Effect.Effect<A, ServerAuthInvalidCredentialError | ServerAuthInternalError, R> =>
530 effect.pipe(
531 Effect.mapError((cause) =>
532 SessionStore.isSessionCredentialInvalidError(cause)
533 ? new ServerAuthInvalidCredentialError({ cause })
534 : new ServerAuthSessionCredentialValidationError({ cause }),
535 ),
536 );
537
538function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null {
539 const header = request.headers["authorization"];
540 if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) {
541 return null;
542 }
543 const token = header.slice(AUTHORIZATION_PREFIX.length).trim();
544 return token.length > 0 ? token : null;
545}
546
547function parseDpopToken(request: HttpServerRequest.HttpServerRequest): string | null {
548 const header = request.headers["authorization"];
549 if (typeof header !== "string" || !header.startsWith(DPOP_AUTHORIZATION_PREFIX)) {
550 return null;
551 }
552 const token = header.slice(DPOP_AUTHORIZATION_PREFIX.length).trim();
553 return token.length > 0 ? token : null;
554}
555
556export const make = Effect.gen(function* () {
557 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
558 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
559 const sessions = yield* SessionStore.SessionStore;
560 const secretStore = yield* ServerSecretStore.ServerSecretStore;
561 const crypto = yield* Crypto.Crypto;
562 const descriptor = yield* policy.getDescriptor();
563
564 const authenticateToken = (
565 token: string,
566 ): Effect.Effect<
567 AuthenticatedSession,
568 ServerAuthInvalidCredentialError | ServerAuthInternalError
569 > =>
570 sessions.verify(token).pipe(
571 Effect.tapError((cause) =>
572 SessionStore.isSessionCredentialInvalidError(cause)
573 ? Effect.logWarning("Rejected authenticated session credential.").pipe(
574 Effect.annotateLogs({
575 reason: cause.message,
576 }),
577 )
578 : Effect.void,
579 ),
580 Effect.map((session) => ({
581 sessionId: session.sessionId,
582 subject: session.subject,
583 method: session.method,
584 scopes: session.scopes,
585 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
586 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
587 })),
588 mapSessionVerificationErrors,
589 );
590
591 const authenticateRequest = (
592 request: HttpServerRequest.HttpServerRequest,
593 ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
594 const cookieToken = request.cookies[sessions.cookieName];
595 const bearerToken = parseBearerToken(request);
596 const dpopToken = parseDpopToken(request);
597 const credential = cookieToken ?? bearerToken ?? dpopToken;
598 if (!credential) {
599 return Effect.fail(new ServerAuthMissingCredentialError({}));
600 }
601 return authenticateToken(credential).pipe(
602 Effect.flatMap((session) => {
603 if (session.proofKeyThumbprint) {
604 if (!dpopToken || dpopToken !== credential) {
605 return Effect.fail(
606 new ServerAuthInvalidCredentialError({
607 diagnostic: "DPoP-bound access token requires DPoP authorization.",
608 }),
609 );
610 }
611 return verifyRequestDpopProof({
612 request,
613 expectedThumbprint: session.proofKeyThumbprint,
614 expectedAccessToken: dpopToken,
615 }).pipe(
616 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
617 Effect.provideService(Crypto.Crypto, crypto),
618 Effect.as(session),
619 );
620 }
621 if (dpopToken) {
622 return Effect.fail(
623 new ServerAuthInvalidCredentialError({
624 diagnostic: "DPoP authorization requires a proof-bound access token.",
625 }),
626 );
627 }
628 return Effect.succeed(session);
629 }),
630 );
631 };
632
633 const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
634 authenticateRequest(request).pipe(
635 Effect.map(
636 (session) =>
637 ({
638 authenticated: true,
639 auth: descriptor,
640 scopes: session.scopes,
641 sessionMethod: session.method,
642 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
643 }) satisfies AuthSessionState,
644 ),
645 Effect.catchIf(isServerAuthCredentialError, () =>
646 Effect.succeed({
647 authenticated: false,
648 auth: descriptor,
649 } satisfies AuthSessionState),
650 ),
651 Effect.withSpan("EnvironmentAuth.getSessionState"),
652 );
653
654 const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = (
655 credential,
656 requestMetadata,
657 ) =>
658 bootstrapCredentials.consume(credential).pipe(
659 Effect.mapError(toBootstrapExchangeError),
660 Effect.flatMap((grant) =>
661 sessions
662 .issue({
663 method: "browser-session-cookie",
664 subject: grant.subject,
665 scopes: grant.scopes,
666 client: {
667 ...requestMetadata,
668 ...(grant.label ? { label: grant.label } : {}),
669 },
670 })
671 .pipe(
672 Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
673 ),
674 ),
675 Effect.map(
676 (session) =>
677 ({
678 response: {
679 authenticated: true,
680 scopes: session.scopes,
681 sessionMethod: session.method,
682 expiresAt: DateTime.toUtc(session.expiresAt),
683 } satisfies AuthBrowserSessionResult,
684 sessionToken: session.token,
685 }) satisfies BootstrapExchangeResult,
686 ),
687 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
688 );
689
690 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
691 (credential, requestedScopes, requestMetadata, input) =>
692 bootstrapCredentials.consume(credential, input).pipe(
693 Effect.mapError(toBootstrapExchangeError),
694 Effect.flatMap((grant) =>
695 Effect.gen(function* () {
696 const grantedScopes = requestedScopes ?? grant.scopes;
697 if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
698 return yield* new ServerAuthScopeNotGrantedError({});
699 }
700 return yield* sessions
701 .issue({
702 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
703 subject: grant.subject,
704 scopes: grantedScopes,
705 ...(input?.proofKeyThumbprint
706 ? {
707 proofKeyThumbprint: input.proofKeyThumbprint,
708 ttl: Duration.hours(1),
709 }
710 : {}),
711 client: {
712 ...requestMetadata,
713 ...(grant.label ? { label: grant.label } : {}),
714 },
715 })
716 .pipe(
717 Effect.mapError(
718 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
719 ),
720 );
721 }),
722 ),
723 Effect.flatMap((session) =>
724 DateTime.now.pipe(
725 Effect.map(
726 (now) =>
727 ({
728 access_token: session.token,
729 issued_token_type: AuthAccessTokenType,
730 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
731 expires_in: Math.max(
732 0,
733 Math.floor(
734 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
735 ),
736 ),
737 scope: encodeOAuthScope(session.scopes),
738 }) satisfies AuthAccessTokenResult,
739 ),
740 ),
741 ),
742 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
743 );
744
745 const issuePairingCredentialForSubject = (input: {
746 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
747 readonly subject: string;
748 readonly label?: string;
749 }) =>
750 createPairingLink({
751 scopes: input.scopes,
752 subject: input.subject,
753 ...(input.label ? { label: input.label } : {}),
754 }).pipe(
755 Effect.map(
756 (issued) =>
757 ({
758 id: issued.id,
759 credential: issued.credential,
760 ...(issued.label ? { label: issued.label } : {}),
761 expiresAt: issued.expiresAt,
762 }) satisfies AuthPairingCredentialResult,
763 ),
764 );
765
766 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
767 "EnvironmentAuth.createPairingLink",
768 )(
769 function* (input) {
770 const createdAt = yield* DateTime.now;
771 const issued = yield* bootstrapCredentials.issueOneTimeToken({
772 scopes: input?.scopes ?? AuthStandardClientScopes,
773 subject: input?.subject ?? "one-time-token",
774 ...(input?.ttl ? { ttl: input.ttl } : {}),
775 ...(input?.label ? { label: input.label } : {}),
776 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
777 });
778 return {
779 id: issued.id,
780 credential: issued.credential,
781 scopes: input?.scopes ?? AuthStandardClientScopes,
782 subject: input?.subject ?? "one-time-token",
783 ...(issued.label ? { label: issued.label } : {}),
784 createdAt: DateTime.toUtc(createdAt),
785 expiresAt: DateTime.toUtc(issued.expiresAt),
786 } satisfies IssuedPairingLink;
787 },
788 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
789 );
790
791 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
792 bootstrapCredentials.listActive().pipe(
793 Effect.map((pairingLinks) => {
794 const excludedSubjects = input?.excludeSubjects ?? [
795 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
796 ];
797 return pairingLinks
798 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
799 .toSorted(
800 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
801 );
802 }),
803 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
804 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
805 );
806
807 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
808 bootstrapCredentials.revoke(id).pipe(
809 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
810 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
811 );
812
813 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
814 sessions
815 .issue({
816 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
817 method: "bearer-access-token",
818 scopes: input?.scopes ?? AuthAdministrativeScopes,
819 client: {
820 ...(input?.label ? { label: input.label } : {}),
821 deviceType: "bot",
822 },
823 ...(input?.ttl ? { ttl: input.ttl } : {}),
824 })
825 .pipe(
826 Effect.map(
827 (issued) =>
828 ({
829 sessionId: issued.sessionId,
830 token: issued.token,
831 method: "bearer-access-token",
832 scopes: issued.scopes,
833 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
834 client: issued.client,
835 expiresAt: DateTime.toUtc(issued.expiresAt),
836 }) satisfies IssuedBearerSession,
837 ),
838 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
839 Effect.withSpan("EnvironmentAuth.issueSession"),
840 );
841
842 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
843 sessions.listActive().pipe(
844 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
845 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
846 Effect.withSpan("EnvironmentAuth.listSessions"),
847 );
848
849 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
850 sessions.revoke(sessionId).pipe(
851 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
852 Effect.withSpan("EnvironmentAuth.revokeSession"),
853 );
854
855 const revokeOtherSessionsExcept: EnvironmentAuth["Service"]["revokeOtherSessionsExcept"] = (
856 sessionId,
857 ) =>
858 sessions.revokeAllExcept(sessionId).pipe(
859 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
860 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
861 );
862
863 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
864 issuePairingCredentialForSubject({
865 scopes: input?.scopes ?? AuthStandardClientScopes,
866 subject: "one-time-token",
867 ...(input?.label ? { label: input.label } : {}),
868 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
869
870 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
871 () =>
872 issuePairingCredentialForSubject({
873 scopes: AuthAdministrativeScopes,
874 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
875 }).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
876
877 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
878 listSessions().pipe(
879 Effect.map((clientSessions) =>
880 clientSessions.map(
881 (clientSession): AuthClientSession => ({
882 ...clientSession,
883 current: clientSession.sessionId === currentSessionId,
884 }),
885 ),
886 ),
887 Effect.withSpan("EnvironmentAuth.listClientSessions"),
888 );
889
890 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
891 "EnvironmentAuth.revokeClientSession",
892 )(function* (currentSessionId, targetSessionId) {
893 if (currentSessionId === targetSessionId) {
894 return yield* new ServerAuthForbiddenOperationError({});
895 }
896 return yield* revokeSession(targetSessionId);
897 });
898
899 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
900 currentSessionId,
901 ) =>
902 revokeOtherSessionsExcept(currentSessionId).pipe(
903 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
904 );
905
906 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
907 issueStartupPairingCredential().pipe(
908 Effect.map((issued) => {
909 const url = new URL(baseUrl);
910 url.pathname = "/pair";
911 url.searchParams.delete("token");
912 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
913 return url.toString();
914 }),
915 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
916 );
917
918 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
919 sessions.issueWebSocketToken(session.sessionId).pipe(
920 Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
921 Effect.map(
922 (issued) =>
923 ({
924 ticket: issued.token,
925 expiresAt: DateTime.toUtc(issued.expiresAt),
926 }) satisfies AuthWebSocketTicketResult,
927 ),
928 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
929 );
930
931 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
932 request,
933 ) =>
934 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
935
936 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
937 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
938 const requestUrl = HttpServerRequest.toURL(request);
939 if (Option.isSome(requestUrl)) {
940 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
941 if (websocketTicket && websocketTicket.trim().length > 0) {
942 return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
943 Effect.map((session) => ({
944 sessionId: session.sessionId,
945 subject: session.subject,
946 method: session.method,
947 scopes: session.scopes,
948 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
949 })),
950 mapSessionVerificationErrors,
951 );
952 }
953 }
954
955 return yield* authenticateRequest(request);
956 });
957
958 return EnvironmentAuth.of({
959 getDescriptor: () =>
960 Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
961 getSessionState,
962 createBrowserSession,
963 exchangeBootstrapCredentialForAccessToken,
964 createPairingLink,
965 issuePairingCredential,
966 issueStartupPairingCredential,
967 listPairingLinks,
968 revokePairingLink,
969 issueSession,
970 listSessions,
971 revokeSession,
972 revokeOtherSessionsExcept,
973 listClientSessions,
974 revokeClientSession,
975 revokeOtherClientSessions,
976 authenticateHttpRequest,
977 authenticateWebSocketUpgrade,
978 issueWebSocketTicket,
979 issueStartupPairingUrl,
980 });
981});
982
983export const layer = Layer.effect(EnvironmentAuth, make).pipe(
984 Layer.provideMerge(PairingGrantStore.layer),
985 Layer.provideMerge(SessionStore.layer),
986 Layer.provideMerge(EnvironmentAuthPolicy.layer),
987);
988
989export const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);
990
991export const runtimeLayer = layer.pipe(Layer.provideMerge(storageLayer));