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
41const 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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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.TaggedError<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
594/** @public Service construction is part of the canonical Effect module API. */
595export const make = Effect.gen(function* () {
596 const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
597 const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
598 const sessions = yield* SessionStore.SessionStore;
599 const secretStore = yield* ServerSecretStore.ServerSecretStore;
600 const crypto = yield* Crypto.Crypto;
601 const descriptor = yield* policy.getDescriptor();
602
603 const authenticateToken = (
604 token: string,
605 ): Effect.Effect<
606 AuthenticatedSession,
607 ServerAuthInvalidCredentialError | ServerAuthInternalError
608 > =>
609 sessions.verify(token).pipe(
610 Effect.tapError((cause) =>
611 SessionStore.isSessionCredentialInvalidError(cause)
612 ? Effect.logWarning("Rejected authenticated session credential.").pipe(
613 Effect.annotateLogs({
614 reason: cause.message,
615 }),
616 )
617 : Effect.void,
618 ),
619 Effect.map((session) => ({
620 sessionId: session.sessionId,
621 subject: session.subject,
622 method: session.method,
623 scopes: session.scopes,
624 ...(session.proofKeyThumbprint ? { proofKeyThumbprint: session.proofKeyThumbprint } : {}),
625 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
626 })),
627 mapSessionVerificationErrors,
628 );
629
630 const authenticateRequest = (
631 request: HttpServerRequest.HttpServerRequest,
632 ): Effect.Effect<AuthenticatedSession, ServerAuthCredentialError | ServerAuthInternalError> => {
633 const credential = selectRequestCredential(
634 request,
635 sessions.cookieName,
636 sessions.legacyCookieName,
637 );
638 if (!credential?.token) {
639 return Effect.fail(new ServerAuthMissingCredentialError({}));
640 }
641 const dpopToken = parseDpopToken(request);
642 return authenticateToken(credential.token).pipe(
643 Effect.flatMap((session) => {
644 if (session.proofKeyThumbprint) {
645 if (!dpopToken || dpopToken !== credential.token) {
646 return Effect.fail(
647 new ServerAuthInvalidCredentialError({
648 diagnostic: "DPoP-bound access token requires DPoP authorization.",
649 dpopFailureReason: "invalid_proof",
650 }),
651 );
652 }
653 return verifyRequestDpopProof({
654 request,
655 expectedThumbprint: session.proofKeyThumbprint,
656 expectedAccessToken: dpopToken,
657 }).pipe(
658 Effect.provideService(ServerSecretStore.ServerSecretStore, secretStore),
659 Effect.provideService(Crypto.Crypto, crypto),
660 Effect.as(session),
661 );
662 }
663 if (dpopToken) {
664 return Effect.fail(
665 new ServerAuthInvalidCredentialError({
666 diagnostic: "DPoP authorization requires a proof-bound access token.",
667 dpopFailureReason: "invalid_proof",
668 }),
669 );
670 }
671 return Effect.succeed(session);
672 }),
673 );
674 };
675
676 const getSessionState: EnvironmentAuth["Service"]["getSessionState"] = (request) =>
677 authenticateRequest(request).pipe(
678 Effect.map(
679 (session) =>
680 ({
681 authenticated: true,
682 auth: descriptor,
683 scopes: session.scopes,
684 sessionMethod: session.method,
685 ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
686 }) satisfies AuthSessionState,
687 ),
688 Effect.catchIf(isServerAuthCredentialError, () =>
689 Effect.succeed({
690 authenticated: false,
691 auth: descriptor,
692 } satisfies AuthSessionState),
693 ),
694 Effect.withSpan("EnvironmentAuth.getSessionState"),
695 );
696
697 const createBrowserSession: EnvironmentAuth["Service"]["createBrowserSession"] = (
698 credential,
699 requestMetadata,
700 ) =>
701 bootstrapCredentials.consume(credential).pipe(
702 Effect.mapError(toBootstrapExchangeError),
703 Effect.flatMap((grant) =>
704 sessions
705 .issue({
706 method: "browser-session-cookie",
707 subject: grant.subject,
708 scopes: grant.scopes,
709 client: {
710 ...requestMetadata,
711 ...(grant.label ? { label: grant.label } : {}),
712 },
713 })
714 .pipe(
715 Effect.mapError((cause) => new ServerAuthAuthenticatedSessionIssueError({ cause })),
716 ),
717 ),
718 Effect.map(
719 (session) =>
720 ({
721 response: {
722 authenticated: true,
723 scopes: session.scopes,
724 sessionMethod: session.method,
725 expiresAt: DateTime.toUtc(session.expiresAt),
726 } satisfies AuthBrowserSessionResult,
727 sessionToken: session.token,
728 }) satisfies BootstrapExchangeResult,
729 ),
730 Effect.withSpan("EnvironmentAuth.createBrowserSession"),
731 );
732
733 const exchangeBootstrapCredentialForAccessToken: EnvironmentAuth["Service"]["exchangeBootstrapCredentialForAccessToken"] =
734 (credential, requestedScopes, requestMetadata, input) =>
735 bootstrapCredentials.consume(credential, input).pipe(
736 Effect.mapError(toBootstrapExchangeError),
737 Effect.flatMap((grant) =>
738 Effect.gen(function* () {
739 const grantedScopes = requestedScopes ?? grant.scopes;
740 if (!grantedScopes.every((scope) => grant.scopes.includes(scope))) {
741 return yield* new ServerAuthScopeNotGrantedError({});
742 }
743 return yield* sessions
744 .issue({
745 method: input?.proofKeyThumbprint ? "dpop-access-token" : "bearer-access-token",
746 subject: grant.subject,
747 scopes: grantedScopes,
748 ...(input?.proofKeyThumbprint
749 ? {
750 proofKeyThumbprint: input.proofKeyThumbprint,
751 ttl: Duration.hours(1),
752 }
753 : {}),
754 // Desktop restarts forget the previous bearer token. Replace
755 // its session, including stale entries left by older versions.
756 replaceActiveForSubjectAndMethod: grant.method === "desktop-bootstrap",
757 client: {
758 ...requestMetadata,
759 ...(grant.label ? { label: grant.label } : {}),
760 },
761 })
762 .pipe(
763 Effect.mapError(
764 (cause) => new ServerAuthAuthenticatedAccessTokenIssueError({ cause }),
765 ),
766 );
767 }),
768 ),
769 Effect.flatMap((session) =>
770 DateTime.now.pipe(
771 Effect.map(
772 (now) =>
773 ({
774 access_token: session.token,
775 issued_token_type: AuthAccessTokenType,
776 token_type: input?.proofKeyThumbprint ? "DPoP" : "Bearer",
777 expires_in: Math.max(
778 0,
779 Math.floor(
780 (session.expiresAt.epochMilliseconds - now.epochMilliseconds) / 1000,
781 ),
782 ),
783 scope: encodeOAuthScope(session.scopes),
784 }) satisfies AuthAccessTokenResult,
785 ),
786 ),
787 ),
788 Effect.withSpan("EnvironmentAuth.exchangeBootstrapCredentialForAccessToken"),
789 );
790
791 const issuePairingCredentialForSubject = (input: {
792 readonly scopes: ReadonlyArray<AuthEnvironmentScope>;
793 readonly subject: string;
794 readonly label?: string;
795 readonly purpose?: "startup";
796 }) =>
797 createPairingLink({
798 scopes: input.scopes,
799 subject: input.subject,
800 ...(input.label ? { label: input.label } : {}),
801 ...(input.purpose ? { purpose: input.purpose } : {}),
802 }).pipe(
803 Effect.map(
804 (issued) =>
805 ({
806 id: issued.id,
807 credential: issued.credential,
808 ...(issued.label ? { label: issued.label } : {}),
809 expiresAt: issued.expiresAt,
810 }) satisfies AuthPairingCredentialResult,
811 ),
812 );
813
814 const createPairingLink: EnvironmentAuth["Service"]["createPairingLink"] = Effect.fn(
815 "EnvironmentAuth.createPairingLink",
816 )(
817 function* (input) {
818 const createdAt = yield* DateTime.now;
819 const issued = yield* bootstrapCredentials.issueOneTimeToken({
820 scopes: input?.scopes ?? AuthStandardClientScopes,
821 subject: input?.subject ?? "one-time-token",
822 ...(input?.ttl ? { ttl: input.ttl } : {}),
823 ...(input?.label ? { label: input.label } : {}),
824 ...(input?.proofKeyThumbprint ? { proofKeyThumbprint: input.proofKeyThumbprint } : {}),
825 ...(input?.purpose ? { purpose: input.purpose } : {}),
826 });
827 return {
828 id: issued.id,
829 credential: issued.credential,
830 scopes: input?.scopes ?? AuthStandardClientScopes,
831 subject: input?.subject ?? "one-time-token",
832 ...(issued.label ? { label: issued.label } : {}),
833 createdAt: DateTime.toUtc(createdAt),
834 expiresAt: DateTime.toUtc(issued.expiresAt),
835 } satisfies IssuedPairingLink;
836 },
837 Effect.mapError((cause) => new ServerAuthPairingLinkCreationError({ cause })),
838 );
839
840 const listPairingLinks: EnvironmentAuth["Service"]["listPairingLinks"] = (input) =>
841 bootstrapCredentials.listActive().pipe(
842 Effect.map((pairingLinks) => {
843 const excludedSubjects = input?.excludeSubjects ?? [
844 INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
845 ];
846 return pairingLinks
847 .filter((pairingLink) => !excludedSubjects.includes(pairingLink.subject))
848 .toSorted(
849 (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
850 );
851 }),
852 Effect.mapError((cause) => new ServerAuthPairingLinksListError({ cause })),
853 Effect.withSpan("EnvironmentAuth.listPairingLinks"),
854 );
855
856 const revokePairingLink: EnvironmentAuth["Service"]["revokePairingLink"] = (id) =>
857 bootstrapCredentials.revoke(id).pipe(
858 Effect.mapError((cause) => new ServerAuthPairingLinkRevocationError({ cause })),
859 Effect.withSpan("EnvironmentAuth.revokePairingLink"),
860 );
861
862 const issueSession: EnvironmentAuth["Service"]["issueSession"] = (input) =>
863 sessions
864 .issue({
865 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
866 method: "bearer-access-token",
867 scopes: input?.scopes ?? AuthAdministrativeScopes,
868 client: {
869 ...(input?.label ? { label: input.label } : {}),
870 deviceType: "bot",
871 },
872 ...(input?.ttl ? { ttl: input.ttl } : {}),
873 })
874 .pipe(
875 Effect.map(
876 (issued) =>
877 ({
878 sessionId: issued.sessionId,
879 token: issued.token,
880 method: "bearer-access-token",
881 scopes: issued.scopes,
882 subject: input?.subject ?? DEFAULT_SESSION_SUBJECT,
883 client: issued.client,
884 expiresAt: DateTime.toUtc(issued.expiresAt),
885 }) satisfies IssuedBearerSession,
886 ),
887 Effect.mapError((cause) => new ServerAuthSessionTokenIssueError({ cause })),
888 Effect.withSpan("EnvironmentAuth.issueSession"),
889 );
890
891 const listSessions: EnvironmentAuth["Service"]["listSessions"] = () =>
892 sessions.listActive().pipe(
893 Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)),
894 Effect.mapError((cause) => new ServerAuthSessionsListError({ cause })),
895 Effect.withSpan("EnvironmentAuth.listSessions"),
896 );
897
898 const revokeSession: EnvironmentAuth["Service"]["revokeSession"] = (sessionId) =>
899 sessions.revoke(sessionId).pipe(
900 Effect.mapError((cause) => new ServerAuthSessionRevocationError({ cause })),
901 Effect.withSpan("EnvironmentAuth.revokeSession"),
902 );
903
904 const revokeOtherSessionsExcept: EnvironmentAuth["Service"]["revokeOtherSessionsExcept"] = (
905 sessionId,
906 ) =>
907 sessions.revokeAllExcept(sessionId).pipe(
908 Effect.mapError((cause) => new ServerAuthOtherSessionsRevocationError({ cause })),
909 Effect.withSpan("EnvironmentAuth.revokeOtherSessionsExcept"),
910 );
911
912 const issuePairingCredential: EnvironmentAuth["Service"]["issuePairingCredential"] = (input) =>
913 issuePairingCredentialForSubject({
914 scopes: input?.scopes ?? AuthStandardClientScopes,
915 subject: "one-time-token",
916 ...(input?.label ? { label: input.label } : {}),
917 }).pipe(Effect.withSpan("EnvironmentAuth.issuePairingCredential"));
918
919 const issueStartupPairingCredential: EnvironmentAuth["Service"]["issueStartupPairingCredential"] =
920 () =>
921 issuePairingCredentialForSubject({
922 scopes: AuthAdministrativeScopes,
923 subject: INTERNAL_ADMINISTRATIVE_BOOTSTRAP_SUBJECT,
924 purpose: "startup",
925 }).pipe(Effect.withSpan("EnvironmentAuth.issueStartupPairingCredential"));
926
927 const listClientSessions: EnvironmentAuth["Service"]["listClientSessions"] = (currentSessionId) =>
928 listSessions().pipe(
929 Effect.map((clientSessions) =>
930 clientSessions.map((clientSession): AuthClientSession => ({
931 ...clientSession,
932 current: clientSession.sessionId === currentSessionId,
933 })),
934 ),
935 Effect.withSpan("EnvironmentAuth.listClientSessions"),
936 );
937
938 const revokeClientSession: EnvironmentAuth["Service"]["revokeClientSession"] = Effect.fn(
939 "EnvironmentAuth.revokeClientSession",
940 )(function* (currentSessionId, targetSessionId) {
941 if (currentSessionId === targetSessionId) {
942 return yield* new ServerAuthForbiddenOperationError({});
943 }
944 return yield* revokeSession(targetSessionId);
945 });
946
947 const revokeOtherClientSessions: EnvironmentAuth["Service"]["revokeOtherClientSessions"] = (
948 currentSessionId,
949 ) =>
950 revokeOtherSessionsExcept(currentSessionId).pipe(
951 Effect.withSpan("EnvironmentAuth.revokeOtherClientSessions"),
952 );
953
954 const issueStartupPairingUrl: EnvironmentAuth["Service"]["issueStartupPairingUrl"] = (baseUrl) =>
955 issueStartupPairingCredential().pipe(
956 Effect.map((issued) => {
957 const url = new URL(baseUrl);
958 url.pathname = "/pair";
959 url.searchParams.delete("token");
960 url.hash = new URLSearchParams([["token", issued.credential]]).toString();
961 return url.toString();
962 }),
963 Effect.withSpan("EnvironmentAuth.issueStartupPairingUrl"),
964 );
965
966 const issueWebSocketTicket: EnvironmentAuth["Service"]["issueWebSocketTicket"] = (session) =>
967 sessions.issueWebSocketToken(session.sessionId).pipe(
968 Effect.mapError((cause) => new ServerAuthWebSocketTokenIssueError({ cause })),
969 Effect.map(
970 (issued) =>
971 ({
972 ticket: issued.token,
973 expiresAt: DateTime.toUtc(issued.expiresAt),
974 }) satisfies AuthWebSocketTicketResult,
975 ),
976 Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
977 );
978
979 const authenticateHttpRequest: EnvironmentAuth["Service"]["authenticateHttpRequest"] = (
980 request,
981 ) =>
982 authenticateRequest(request).pipe(Effect.withSpan("EnvironmentAuth.authenticateHttpRequest"));
983
984 const authenticateWebSocketUpgrade: EnvironmentAuth["Service"]["authenticateWebSocketUpgrade"] =
985 Effect.fn("EnvironmentAuth.authenticateWebSocketUpgrade")(function* (request) {
986 const requestUrl = HttpServerRequest.toURL(request);
987 if (Option.isSome(requestUrl)) {
988 const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
989 if (websocketTicket && websocketTicket.trim().length > 0) {
990 return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
991 Effect.map((session) => ({
992 sessionId: session.sessionId,
993 subject: session.subject,
994 method: session.method,
995 scopes: session.scopes,
996 ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
997 })),
998 mapSessionVerificationErrors,
999 );
1000 }
1001 }
1002
1003 return yield* authenticateRequest(request);
1004 });
1005
1006 return EnvironmentAuth.of({
1007 getDescriptor: () =>
1008 Effect.succeed(descriptor).pipe(Effect.withSpan("EnvironmentAuth.getDescriptor")),
1009 getSessionState,
1010 createBrowserSession,
1011 exchangeBootstrapCredentialForAccessToken,
1012 createPairingLink,
1013 issuePairingCredential,
1014 issueStartupPairingCredential,
1015 listPairingLinks,
1016 revokePairingLink,
1017 issueSession,
1018 listSessions,
1019 revokeSession,
1020 revokeOtherSessionsExcept,
1021 listClientSessions,
1022 revokeClientSession,
1023 revokeOtherClientSessions,
1024 authenticateHttpRequest,
1025 authenticateWebSocketUpgrade,
1026 issueWebSocketTicket,
1027 issueStartupPairingUrl,
1028 });
1029});
1030
1031export const layer = Layer.effect(EnvironmentAuth, make).pipe(
1032 Layer.provideMerge(PairingGrantStore.layer),
1033 Layer.provideMerge(SessionStore.layer),
1034 Layer.provideMerge(EnvironmentAuthPolicy.layer),
1035);
1036
1037const storageLayer = Layer.mergeAll(ServerSecretStore.layer, SqlitePersistenceLayer);
1038
1039export const runtimeLayer = layer.pipe(
1040 Layer.provideMerge(storageLayer),
1041 Layer.provideMerge(ServerEnvironment.identityLayer),
1042);