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